0% found this document useful (0 votes)
10 views28 pages

C

C INTRODUCTION

Uploaded by

principal.sbvrdc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views28 pages

C

C INTRODUCTION

Uploaded by

principal.sbvrdc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT-I

INTRODUCTION TO ALGORITHMS AND


PROGRAMMING LANGUAGES

ALGORITHM:
An algorithm is a step-by-step description of how to arrive at a solution. An algorithm
provides a blueprint for writing a program to solve a particular problem. Once we have an
idea or a blueprint of a solution, we can implement it in any high-level language, such as C,
C++, JAVA, and so on.
Characteristics of Algorithm:
1. Be precise
2. Be unambiguous
3. It looks like normal English.
4. Not even a single instruction must be repeated infinitely
5. After the algorithm gets terminated, the desired result must be obtained.

CONTROL STRUCTURE USED IN ALGORITHMS:


An algorithm uses three control structures, namely sequence, decision, and repetition.
1. Sequence: Sequence means that each step of the algorithm is executed in the
specified order.
An algorithm to add two numbers is given below
Step 1: Input the first_number as A
Step 2: Input the second_number as B
Step 3: Set sum=A+B
Step 4: Print sum
Step 5: End
2. Decision: Decision statements are used when the execution of a process depends on
the outcome of some condition.
For example, if x=y then print “equal”. Hence, the general form of the if construct is
given as:
if condition then process
A decision statement can also be stated in the following manner:
if condition
then process 1
else process 2
An algorithm to check the equality of two numbers is shown below
Step 1: Input the first_number as A
Step 2: Input the second_number as B
Step 3: if A= =B
Then print “Equal”
else
print “not equal”
Step 4: End

1
UNIT-I

3. Repetition: Repetition involves executing one or more steps for a number of times.
This can be implemented using constructs such as while, do-while, and for loops.
These loops execute one or more steps until some condition is true.
Algorithm to first 10 natural numbers
Step 1: [initialize] Set I=1, N=10
Step 2: Repeat steps 3 and 4 while I<=N
Step 3: print I
Step 4: set I=I+1
Step 5: End

SOME MORE ALGORITHMS

Swapping two values Larger of two values


Solution: Solution:
Step 1: Input first_number as A Step 1: Input first_number as A
Step 2: Input second_number as B Step 2: Input second_number as B
Step 3: set temp=A Step 3: if A > B
Step 4: set A=B then print A
Step 5: set B=temp else if A < B
Step 6: print A, B then print B
Step 7: End else
print “ the numbers are equal”
Step 5: End
Printing the grade of student
Solution:
Step 1: Enter marks as M
Step 2: if M > 75
then print “0”
step 3: if M > =60 and M < 75
then print “A”
step 4: if M >=50 and M < 50
then print “B”
step 5: if M > =40 and M < 50
then print “C”
else print “ D”
step 6: End

FLOWCHARTS:
A flowchart is a graphical representation of a process.
2
UNIT-I

When designing a flowchart, each step in the process is shown by different symbol and is
associated with a short description. The symbols in the flowchart are linked together with
arrows to show the flow of logic in the process.

The symbols of a flowchart include:


 Start and end symbols are also known as the terminal symbols and are represented as
circles, ovals, or rounded rectangles. Terminal symbols are always the first and the
last symbol in a flowchart.
 Arrows show the flow of control of the program.
 Generic processing step, also called as activity, is represented using a rectangle.
Activities include instructions.
 Input/Output symbols are represented using a parallelogram and are used to get inputs
from the user or display the results to them.
 A conditional or decision symbol is represented using a diamond. It is basically used
to show yes/no question or a true/false test.

Significance of flowcharts:
 A flowchart is a graphical representation of the process.
 It is usually drawn in the early stage of the programming.
 Once a flow chart is drawn, programmers can understand the logic of the problem.
 Once a flow chart is drawn, it becomes easy for the programmers to write the program
in any high-level language.
 A flowchart follows top-down approach in solving problems.
 They act as a guide or blueprint for the programmers to code the solution in any
programming language. They direct the programmers to go from the starting point of
the program to the ending point without missing any step.
 They can be used to debug programs that have error(s). They help the programmers to
easily detect, locate and remove mistakes in the program in systematic manner.

Limitations:
 Drawing flowchart is laborious and time consuming activity.
 Often, the 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.

3
UNIT-I

4
UNIT-I

PROGRAMMING LANGUAGES:
Language is the communication media, Human languages (eg. Telugu, English, Hindi etc) are
used to establish communication between person to person where as computer languages are
used to establish the communication between the person and machine. The computer
languages are divided into the following:
Computer Languages

Machine Level Assembly Level High Level


Languages Languages Language
Machine Level Languages: This language is also called 1 st Generation Language. All the
instructions in this language are in the form 0’s and 1’s. It is difficult to learn and difficult to
understand. This is also called as low level language. Computer understands machine
language instructions directly.
Advantages:
1. Program execution is faster.
2. No translation is required.
3. The computer can understand instructions directly.
Disadvantages:
1. Machine dependent languages
2. Programming is very difficult
3. Difficult to understand
4. Difficult to write bug free programs
Assembly Level Language: This language is also called as 2 nd Generation Language. All the
instructions are written in Assembly level languages are in the form of mnemonics.
Mnemonic means symbolic name. ADD for addition, MUL for multiplication, SUB for
subtraction, DIV for division etc. So, there is a need of translator (Assembler). Assembler is a
system, which translate assembly level instructions in to machine understandable form.
Advantages:
1. Easy to understand when compared to Machine level languages.
2. Easy to modify.
Disadvantages:
1. Machine dependent language.
2. Requires translator.
3. Difficult to write
High Level Languages: All the instructions are written in High level languages are in the
form of general English. These languages are very easy to learn and easy to implement. But it
also requires the translator to translate these programs into machine understandable form.
Advantages:
1. Easy to write and understand
2. Easy to debug.
3. Machine independent language
Disadvantages:
1. Need translator.
2. Requires more execution time.

5
UNIT-I

Difference b/w machine, assembly, high level languages


Features Machine Assembly High level
Form 0’s and 1’s Mnemonic codes Normal English
Machine dependent Dependent Dependent Independent
Translator Not needed Needed Needed
Execution time Less Less High
Languages Only one Different Different languages
manufactures
Nature Difficult Difficult Easy
Memory space Less Less more

GENERATIONS OF PROGRAMMING LANGUAGES:


As we know that programming languages are the primary tool for creating software. The
concept of generations of programming languages is closely connected to the advance in
technology. The five generations of programming languages include machine language,
assembly language, high-level language, very high-level language, and artificial intelligence.

First Generation: Machine Languages


This is the lowest level of programming languages and is the only language that a computer
understands. All the command and data values are expressed using 0’s and 1’s.
Advantages Disadvantages
1. Code can be directly executed by 1. Code is difficult to write
the computer. 2. Code is difficult to understand by
2. Execution is fast and efficient other people
3. Programs can be written to 3. Code is difficult to maintain
efficiently utilize memory 4. There is more possibility for
errors to creep in.
5. It is difficult to detect and correct
errors.
6. Code is machine dependent and
thus non-portable

Second Generation: Assembly Language


Assembly languages use symbolic notations to represent machine language instructions.
Since, it is close to machine language, assembly language is also a low-level language. It
used symbolic codes, also known as mnemonic codes, which are easy-to-remember
abbreviations, rather than numbers. Examples of these codes include ADD for add, CMP for
compare and MUL for multiply.
Assembly language statements or program consists of a label, an operation code, and
one or more operands.
Labels are used to identify and refer instructions in the program. The operation code
is a mnemonic code such as ADD, MOVE. The operand specifies the register.

6
UNIT-I

Programs written in assembly language need a translator often known as assembler, to


covert them into machine language.
Assembler: A special program called assembler is required to convert the
code written in assembly language into an equivalent code in machine language. The
assembler takes an assembly language program as input and gives a code in machine
language as output. It there is an error, the assembler gives a list of errors. The object
file is created only when the assembly language code is free from errors. The object
file can be executed as and when required.

Advantages Disadvantages

1. It is easy to understand. 1. Code is machine dependent and


2. It is easier to write programs in thus non-portable.
assembly language than in 2. Programmers must have a good
machine language. knowledge of the hardware and
3. It is easy to detect and correct internal architecture of the CPU.
errors. 3. The code cannot be directly
4. It is easy to modify. executed by the computer.
5. It is less prone to errors.

Third Generation: High-level Language


Third-Generation programming languages are a modification of 2GLs. The third generation
was introduced to make the languages more programmers friendly. Programs were written in
languages that were more English-like, making them more convenient to use. High-level
programming languages make a complex programming simpler and easier to read, write and
maintain.
A translator is needed to translate the instructions written in high-level language into
the computer-executable machine language. Such translators are commonly known as
interpreters and compilers. Programs written in such languages are portable between
machines. For example, a program written in standard C can be compiled and executed on
any computer that has a standard C compiler. BASIC, FORTAN, PASCAL, COBOL, C, C++
and JAVA are few examples of third generation programming languages.

Advantages Disadvantages
1. The code is machine independent. 1. Code may not be optimized.
2. It is easy to learn and use the 2. The code is less efficient.
language. 3. It is difficult to write a code that
3. There are few errors. controls the CPU, memory and
4. It is easy to document and understand registers.
the code.
5. It is easy to maintain the code.
6. It is easy to detect and correct errors.

7
UNIT-I

Fourth Generation: Very High-level Languages


Fourth generation programming languages are non-procedural. While using non-procedural
language, programmers define what they want the computer to do but they do not supply all
the details of how it has to be done.
4GL characteristics:
1. The instruction of the code is written in English-like sentences.
2. They are non-procedural, so users concentrate on the ‘what’ instead of the ‘how’
aspect of the task.
3. The code written in 4GL is easy to maintain.
4. The written in 4GL enhances the productivity of the programmers.
A typical example of the 4GL is the query language, which allows a user to request
information from a database. A very high-level language is usually limited to specific
application and uses syntax that is never used in other programming languages.

Fifth Generation Programming Language:


Fifth generation programming languages are centred on solving problems using the
constraints given to a program rather than using an algorithm written by a programmer. Most
constraint-based and logic programming languages and some declarative languages form part
of 5GLs. These languages are widely used in artificial intelligence research. It contains visual
tools to help to develop a program. Examples of 5GLs include prolog, Mercury and Visual
Basic.
Fifth generation programming allows people to interact with computers without
needing any specialised knowledge. People can talk to computers and the voice recognition
systems can convert spoken sounds into written words.

Difference between compiler and interpreter


Compiler Interpreter
1. It translates the entire program in one 1. It interprets and executes one
go. statement at a time.
2. It generates error(s) after translating 2. It stops translation after getting the
the entire program. first error.
3. Execution of code is faster. 3. Execution of code is slower as every
time reinterpretation of statements has
to be done.
4. An object file is generated. 4. No object file is generated.
5. Code need not be recompiled every 5. Code has to be reinterpreted every
time it is executed. time it is executed.
6. It merely translates the code. 6. It translates as well as executes the
code.
7. It requires some memory space. 7. It requires less memory space.

8
UNIT-I

CATEGORIZATION OF HIGH-LEVEL LANGUAGES


High-level languages can be easily categorized into four groups.
High-level language
Unstructured programming
Structured programming Logic-oriented programming Object-oriented programming

Unstructured Programming:
In unstructured programming, programmers write small and simple programs consisting only
of one main program. Here, main() consists of statements that modify the data that is global
throughout the whole program. Though this technique is simple, it is not good for writing
large programs. For example, if we need to perform a particular task multiple times in a
program, then we need to copy the same sequence of statements at different locations within
the program. This led to the idea of writing functions or procedures. The new technique of
using procedures came to be known as procedural programming.

Structured Programming:
The concept of structured programming also referred to as modular programming. Structured
programming employs a top-down approach in which the overall program structure is broken
down into separate modules. This allows the code to be efficiently loaded into the memory
and to be reused in other programs. Modules are coded separately, and once a module is
written and tested individually, it is then integrated with the other modules to form the overall
program structure. In structured programming, the program flow follows a simple sequence
and usually avoids the use of goto statement. Besides sequential flow, structured
programming also supports selection and repetition. Selection allows for choosing any one of
a number of statements to execute based on the current status of the program. Selection
statements contain keywords such as if, then, endif, and switch. In repetition, a selected
statement remains active until the program reaches a certain point. It includes keywords such
as repeat, for, and do until.
Advantages:
1. The goal of structured programming is to write correct programs that are easy to
understand and modify.
2. A structured program can be written in less time than an unstructured program.
Modules or procedures written for one program can be reused in other programs as
well.
3. A structured program is easy to debug. This is because each procedure is allowed to
perform just one task and therefore, every procedure can be checked individually for
any error.
4. Every procedure in a structured program has meaningful names and has clear
documentation of a task to be performed. This is clearly understood by another
programmer.

9
UNIT-I

Logic-oriented Programming Language:


Logic-oriented programming languages use a programming paradigm that is based on
formal predicate logic. The logic paradigm is different from other programming
paradigms. The predicate logic describes the nature of a problem by defining the
relationships between rules and facts.

Object-oriented programming:
Unstructured and structured programming paradigms are task-based. The object-
oriented paradigm is both task-based and data-based. All the relevant data and tasks
are grouped together in entities known as objects. The major objective of object-
oriented approach is to eliminate some of the defect encountered in the procedural
approach. OOP treats data as critical element in the program development and does
not allow it to flow freely around the system.

Concepts of Object-oriented Programming:


1. Class
2. Object
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Class: A class is used to describe real-world things. It provides a template or blueprint
that describes the structure and behaviour of a set of similar object.
Object: Objects are basic run time entities in an object oriented programming. An object
may be defined as an identifiable entity with some state and behaviour.
Inheritance: Inheritance is one of the most powerful features of OOP’s. Inheritance is a
process of creating a new class from the existing class. The new class inherits all the
capabilities of the existing class.
Polymorphism: Polymorphism comes from the Greek words “Poly” and “morphism”,
“Poly” means many and “Morphism” means form i.e., many forms.

SHAPE

CIRCLE RECTANGLE TRIANGLE


Encapsulation: Binding of data and functions into a single component is known as
encapsulation. The data is not accessible by outside functions.
Data abstraction: Data abstraction refers to the process of defining data and functions in
such a way that only the essential details are provided to the outside world and the
implementation details are hidden.

10
UNIT-I

SOME POPULAR HIGH-LEVEL LANGUAGES

1. BASIC:
BASIC (Beginners All-purpose symbolic Instruction Code) is a general purpose high-
level programming language developed in the 1964 by John G.Kemeny and Thomas.
In 1960s, programming was done only by scientists and mathematicians. BASIC was
specially designed to enable students in fields other than science and mathematics to
use computers. It was easy to learn and was very powerful language that was used for
wide range of applications. In 1970s BASIC was widely used in microcomputers.

2. FORTRAN:
FORTRAN (Formulas Translation) is one of the oldest general purpose programming
languages. It was developed in 1957 at IBM by John Backus. The development of
FORTRAN was remarkable development in the field of programming languages. It is
a machine independent, simple language suitable for a wide variety of applications
that combined a form of English shorthand with algebraic equation. It is extensively
used in areas such as weather prediction, finite element analysis. It is also used in
programming video games, air traffic control system.

3. Pascal:
Pascal is a procedural programming language developed in the late 1960s. It is a small
and efficient language specifically designed to encourage good programming. The
structure and syntax of Pascal is similar to that of C. Pascal provided many features
that were lacking in other languages. Pascal contains built-in data types, user-defined
data types, and defined set of data structures.

4. C
C is a high-level general-purpose programming language that was developed in 1970s
by Dennis Ritchie at Bell Labs. C is considered as a powerful and flexible
programming language that can be used for wide range of applications varying from
business programs to engineering. It is relatively small requires less memory. It is
easy to understand. It is easily portable.

5. C++
C++ is a general-purpose programming language developed by Bjarne Stroustrup
starting in 1979 at Bell Labs. Like C, C++ is an intermediate-level language because
it comprises both high-level and low-level language features. It is a powerful
language implemented on a wide variety of hardware and operating system platforms.
It is a superset of the C language. It is an object oriented programming. It allows the
programmers to reuse the existing code. In C++ it is easy to write, debug and modify
a code.

11
UNIT-I

6. JAVA
Java is a general-purpose object-oriented programming language released by Sun
Microsystems in 1995. It is a powerful language than C++ and other high-level
languages. Programs written in Java are robust, secure, and reliable. Java was used in
Internet applications (games, chatting), Desktop publishing (Viewing images in 3D),
Embedded system applications, Intranet applications and other e-business solutions.
Java program follow write once, run anywhere (WORA). Java source code files (with
.java extension) are compiled into a bytecode (with a .class extension), which can then
be executed by a Java interpreter.

7. LISP
LISP (List processing), is one of the oldest programming language still widely used
by programmers all over the world. List processing (Lisp) allows programs to easily
manipulate non-numeric data such as symbols and strings of text. LISP’s ability to
manipulate symbolic expressions rather than numbers makes it convenient for
artificial intelligence applications and for simulation of games.

FACTORS AFFECTING SELECTION OF PROGRAMMING LANGUAGE

Organizational Policies: Organizations have policies that dictate which computer hardware
and software they should use. For example, many organizations have Java as the default
programming language.
Suitability: The programming language must be able to work on the platform being used.
Availability of programmers: The choice of programming language also depends on the
programmer’s experience and expertise. If a new language that is new to the programmer is
chosen, then it would demand more investment in terms of time and money because either the
programmer will have to be trained in the language or some new programmer having a sound
knowledge of that language would be hired. In both cases, extra time and money will be
required.
Reliability: Some programming languages have built-in features that support the
development of the software that is reliable and less prone to crash. A reliable code can
withstand even in stress conditions.
Development costs: Development cost should be considered while choosing a programming
language.
Speed of development: Speed of development is a factor that not only includes the time it
takes to write a code but also considers the time taken to find a solution to the problem.
Object orientation: In some situations, object-oriented programming to code a solution is far
more beneficial than coding with a traditional language. This is because it not only speeds up
the development process because of the existing code that can be reused.
Elasticity: The elasticity of the language makes easy to add new features to the existing
program.
Performance: The performance of a language is to be considered.

12
UNIT-I

Speed requirements: Different languages take different times to execute. The time to
execute a code also depends on whether the language in which it is written is compiled,
assembled or interpreted.
GUI requirements: Some languages have a in-built support for GUI, whereas others either
do not have or have very little support for GUI. If a program that needs GUI, then the code
will be very lengthy and complex.

PSEUDOCODE
Pseudocode is a form of structured English that describes algorithms. It allows designers to
focus on the logic of the algorithm without getting stuck down by the details of language
syntax. The pseudocode purpose is to enhance human to understand the solution. This helps
even non-programmers to understand the logic of the designed solution. There are no
standards defined for writing a pseudocode.
Keywords used while writing pesudocode
For looping and selection, the designer must include the keywords Do while…EndDO; Do
until … EndDo; Case … EndCase; If … EndIf;
Parts of Pseudocodes:

1. If-Then: If the condition is true the statements in the Then clause executes.
Syntax:
If condition Then
Statements
End If

Ex: If age > =18 Then


Print “ eligible to vote”
End if

2. If-Then-Else: If the condition is true the statements in Then clause executes,


otherwise, statements in else clause executes.
Syntax:
If condition Then
Statement 1
Else
Statement 2
End If

Ex: If a>b Then


Print “ a is big”
Else
Print “ b is big”
End if

13
UNIT-I

3. Case Type: To make a decision from number of choices we use Case type.
Syntax:
CASE expression OF
Case 1: statement 1
Case 2: statement 2
------
Case n: statement n
Others:
Default statement
End Case

Ex: Case day OF


1. Print “ Sunday”
2. Print “Monday”
--
7. print “Saturday”
End case

While: The statements of a loop will execute as long as the condition is true.
Syntax:
While condition
Statement
End while
Ex: while i<=10
Print i
Increment i
End while

Examples:

Calculating the price of a product adding sales tax to its original price.
1. Read the price of the product.
2. Read the sales tax rate
3. Calculate sales tax= price of
the item × sales tax rate.
4. Calculate total price= price of
the product + sales tax.
5. Print total price.
6. End
Variables: price of the product, sales
tax rate, sales tax, total price

14
UNIT-I

Difference between procedural and non-procedural language?


Procedural Non-procedural
1. These are third generation languages. 1. These are fourth generation languages.
2. Procedural languages concentrate on 2. Non-procedural languages concentrate
what you want to do and how to do it. on what you want to do rather than how
3. Manipulate only individual data items. to do it.
4. BASIC, COBOL, C and FORTRAN are 3. Manipulate group of items as a group
few examples. rather than individually.
5. Programming effort increases. 4. SQL, PowerBuilder, Delphi, SAS are
6. The cost of Software developed in 3GL some examples.
is high. 5. Programming effort is reduced.
6. The cost of Software developed in 4GL
is low.

15
UNIT-I

C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It


was designed and written by a man named Dennis Ritchie. In the late seventies C began to
replace the more familiar languages of that time.

HISTORY OF C

The root of modern language is ALGOL, introduced in the early 1960’s. It was first computer
language to use a block structure. Although it never became popular in USA, it was widely
used in Europe. ALGOL gave the concept of structured programming.

In 1967, Martin Richards developed a language called


BCPL (Basic Combined Programming Language)
primarily used for writing system software.

In 1970, Ken Thompson created a language using


many features of BCPL and called it simply B. B was
used to create early versions of UNIX operating
system at Bell Laboratories.

C was evolved from ALGOL, BCPL, and B by


Dennis Ritchie at the Bell Laboratories in 1972. C
uses many concepts from these languages and added
the concept of data types and other powerful features.

Brian Kerningham and Dennis Ritchie published a


book “The C Programming Language”, later the
language came to be known as “K&R C”

In 1983 ANSI (American National Standards


Institute) appointed a committee, this committee approved a version of C in 1989 which is
now known as ANSI C. In 1990 it was approved by the International Standards Organization
(ISO) and this version of C is also referred to C89.

FEATURES OF C

1. Simple: C is a simple language in the sense that it provides structured approach (to
break the problem into parts), rich set of library functions, data types etc.
2. Portable: This feature refers to use of C language program on different platforms
without any change in configuration.
3. Structured Programming Language: C is a structured programming language in the
sense that we can break the program into parts using functions. So, it is easy to
understand and modify.
4. Speed: The compilation and execution time of C language is fast.
5. Extensible: C language is extensible because it can easily adopt new features
6. Case Sensitive: C is a case sensitive, that is it can differentiate the character is either
upper case or lower case.

16
UNIT-I

7. Pointer: C provides the feature of pointers. We can directly interact with the memory
by using the pointers.
8. Recursion: In C, we can call the function within the function.
9. Rich Library: C provides a lot of in-built functions that makes the development fast.
10. Memory Management: It supports the feature of dynamic memory allocation.

STRUCTURE OF C PROGRAM

Documentation Section
Link Section
Definition Section
Global Declaration Section
main( ) Function Section
{
Declaration Part
Executable Part
}
Subprogram section
Function-1
Function-2
.
.
. (User-defined funtions)
.
Funtion-n
 The documentation section consist of a set of comments lines.
 The link section provides instructions to the compiler to link functions from the
system library.
 The definition section defines all symbolic constants.
 The global declaration section contains variables that can be used in more than one
function and we call these variables as global variables.
 Every C program must have one main() function section. This section contains two
parts declaration and executable part. The program execution begins at the opening
brace and ends at the closing brace. The closing brace is the logical end of the
program. All the statements in the declaration and executable parts end with
semicolon (;).
 Subprogram section contains all the user-defined functions that are called in the main
function.

FIRST C PROGRAM
#include <stdio.h>
#include <conio.h>
main()
{
printf("Hello C Language");
getch();
}

17
UNIT-I

#include <stdio.h> includes the standard input output library functions. The printf() and
scanf() functions are defined in stdio.h .
#include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.

COMPILING AND EXECUTING C PROGRAM


If you are using a Turbo C or Turbo C++ compiler here are the steps that you need to follow
to compile and execute your first C program…
 Start the compiler at C> prompt. The compiler (TC.EXE is usually present in C:\TC\
BIN directory).
 Select New from the File menu.
 Type the program.
 Save the program using F2 under a proper name (say Program1.c).
 Use Ctrl + F9 to compile and execute the program.
 Use Alt + F5 to view the output.
Note that on compiling the program its machine language equivalent is stored as an EXE file
(Program1.EXE) on the disk. This file is called an executable file.

CHARACTER SET
A character set denotes any alphabet, digit or special symbol used to represent information.
Alphabets A, B, ….., Y, Z
a,b ……, y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols ~‘!@#%^&*()_-+=|\{}
[]:;"'<>,.?/

COMMENTS
Comments are like helping text in your C program and they are ignored by the compiler.
There are two types of comments.
1. Single Line Comments
2. Multi Line Comments
Single line comments are represented by double slash //.
Example: // printing information
Multi line comments are represented by slash asterisk /*…*/. It occupies of many lines of
code.
Example:
/*
Code
To be commented
*/
C TOKENS
The smallest individual units in a program are known as tokens. C has the
following tokens.
 Keywords

18
UNIT-I

 Identifiers
 Constants
 Strings
 Special symbols
 Operators

KEYWORDS
The following list shows the reserved words in C. These reserved words may not be used as
constants or variables or any other identifier names. There are 32 keywords.

auto break case char const Continue default do


double else enum extern float For goto if
int long register return short Signed sizeof static
struct switch typedef union unsigned Void volatile while

IDENTIFIERS
Identifier refers to the name of variables, functions and arrays. These are the user-defined
names and consist of a sequence of letters and digits, with a letter as a first character. Both
uppercase and lowercase letters are permitted. The underscore character is also permitted in
identifiers.
Rules for identifiers:
1. First character must be an alphabet (or underscore).
2. Must consist of only letters, digits, or underscore.
3. Cannot use a keyword.
4. Must not contain white space
5. Only first 31 characters are significant.
CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a program. C
supports types of constants as explained below:

CONSTANTS

NUMERIC CONSTANTS CHARACTER


SINGLE CONSTANTS
INTEGER REAL CHARACTE STRING
CONSTANT CONSTANT R CONSTANT
S S CONSTANT S
S

Integer Constants:
An integer constant refers to a sequence of digits. There are three types of integers, namely,
decimal integer, octal integer and hexadecimal integer
Decimal integer: It consists of a set of digits, 0-9. It may be either positive or negative.
Ex: 3445, 123, -123, -56, 0

19
UNIT-I

Octal integer: It consists of any combination of digits from the set 0 to 7 with a leading
0. Octal values have sign
Ex: 034, 037, 0551
Hexadecimal integer: It consists of a set of digits 0 to 9 and alphabets A to F to represent
the values of 10 to 15. Each Hexadecimal value begins with 0x.
Ex: 0x20xF5, 0x2, 0x9F

Real Constants:
A real constant refers to numbers containing fractional parts like 17.4. Such numbers are
called real (or floating point) constants.
A real number may also be expressed in exponential notation.
Ex: 2.1565e2

e2 means multiply the number by 102.


then the above value becomes 215.65
The general form for is :
mantissa e exponent

Single Character Constants:


Any single character or symbol or digits enclosed within a pair of single quote marks is called
single character constant.
Ex: ‘B’, ‘3’, ‘!’

String Constants:
A string constant is a sequence of characters enclosed between double quotes. The characters
may be alphabets, digits, special characters and blank spaces.
Ex: “Ashwika”, “2016”, “ MAY1”

Backslash Character Constants:


C supports some special backslash characters constants that are used in output functions.
Constant Meaning
‘\b’ Back space
‘\f’ Form feed
‘\n’ New line
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\’’ Single quote
‘\”’ Double quote
‘\\’ Black slash
‘\a’ Audible alert
‘\v’ Vertical tab
VARIABLE
A variable is a name of memory location. It is used to store data. A variable takes different
values at different times during execution. The syntax of variable:
Type variable_list;
Example of declaring a variable is given below:

20
UNIT-I

int a;
float b;
char c;
From above a, b, c are variables and int, float, char are data types.
Rules for defining variables:
o A variable can have alphabets, digits and underscore.
o A variable name can start with alphabet and underscore only. It can't start with digit.
o No white space is allowed within variable name.
o A variable name must not be any reserved word or keyword e.g. int, float etc.

DATA TYPES
Data types specify what type of data we enter into our programs. C language has some
predefined set of data types. These data types have different storage capacities.
C language supports data types like
Primary data types: These are fundamental data types in C namely integer (int), floating
(float), character (char) and void
Derived data types: Derived data
types are like arrays, unions,
structures and pointers.
User-Defined data types: User-
Defined data types like Typedef,
Enum.

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

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 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

21
UNIT-I

double 8 1.7E-308 to 1.7E+308

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

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.

I/O STATEMENTS IN C
C programming language provides many of the built-in functions to read given input and
write data on screen, printer or in any file.
These built-in functions are available in “stdio.h” and “conio.h” header files.
The I/O functions are classified into 2 categories as shown below:
I/O FUNCTIONS

Formatted I/O Unformatted I/O

scanf() getchar() putchar()


printf() gets() puts()

Scanf(): It is a formatted input function which is used to accept data from the user (keyboard)
at run time. The given data is transferred to the memory and is stored in the specified
variables.
Syntax: scanf (“format-string”, &varl , &var2... &var-n);

Printf(): The printf ( ) function is a formatted output function that is used to display the
given information on the standard output device. It is used to print numbers, characters and
strings or combination of the above along with appropriate message.
The syntax of this function can be anyone of the following: #include<stdio.h>
Syntax-1: printf (“format-string”); Syntax-2: printf #include<conio.h>
(“format-string”, values-list); main()
{
In the above syntax, the 'values-list' can be variables, int x;
constants, or expressions separated by commas. The 'format- printf(" Enter the value ");
string' is a string constant that contains the following: scanf("%d",&x);
printf(" The value of x is %d ",x);
char i;
22 i=getchar();
putchar(i);
getch();
}
UNIT-I

I. Any character in the 'C' character set.


II. Format characters that begin with '%' symbol
III. Escape sequence characters that begin with ‘\’ symbol.

Getchar (): This is an unformatted I/O function which is used to accept a character from the
keyboard and stores in a variable.
Syntax: variable=getchar();

Putchar (): This is an unformatted I/O function which is used to print a character on the
standard output device. i.e. monitor.
Syntax: putchar(arg)

#include<stdio.h>
Gets(): This is an unformatted I/O function which is used to
#include<conio.h>
accept a string from the keyboard and stores in a variable. It main()
reads characters until Enter is pressed. It stores null character {
‘\0’ at the end of the string.
Syntax: gets(variable); char a[8];
gets(a);
Puts(): This is an unformatted I/O function which is used to puts(a);
getch();
print a string on the monitor.
}
Syntax: puts(variable);

OPERATORS
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables.
C operators can be classified into following types,
1. Arithmetic operators
2. Relation operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

An expression is a sequence of operand and operators that reduces to a single value.


1. Arithmetic operators: Arithmetic operators are used to perform arithmetic
calculations.

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division (which returns quotient value)

23
UNIT-I

% Modulo division (which returns reminder value)


Example:
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c;
a=20,b=3,c=2;
printf(" \n The sum of a, b, and c is %d ",(a+b+c));
printf(" \n The subtraction of a and b is %d ",(a-b));
printf(" \n Multiplication of a and b and c is %d ",(a*b*c));
printf(" \n Division of a and b is %d ",a/b);
printf(" \n Modulo of a and b is %d ",a%b);
getch();
}

Integer Arithmetic:
When both the operands in a single arithmetic expression are integers, the expression is
called an integer expression, and the operation is called integer arithmetic.
Example:
a=14 and b =4
a-b=10, a+b=18, a*b=56, a/b=3(decimal part truncated), a%b=2 (remainder of integer
division)
Real Arithmetic: An arithmetic operation involving only real operands is called real
arithmetic.
Example:
X=6.0/7.0 = 0.857143
Mixed-mode Arithmetic:
When one of the operands is real and the other is integer, the expression is called a mixed-
mode arithmetic expression.
Example:
15/10.0=1.5
2. Relational operators: The relational operators are used to compare two values and
gives either true (1) or false (0) result. The following are the relational operators.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Example:
#include<stdio.h>
#include<conio.h>
main()

24
UNIT-I

{
int a,b;
a=20,b=3;
printf(" \n a>b %d ",a>b);
printf(" \n a<b %d ",a<b);
printf(" \n a==b %d ",a==b);
printf(" \n a<=b %d ",a<=b);
printf(" \n a>=b %d ",a>=b);
printf("\n a!=b %d ",a!=b);
getch(); }

3. Logical operators: These are used to combine two or more relational expressions and
give the result either true or false.

Operator Meaning
&& Logical and
|| Logical or
! Logical not

Truth table for AND Truth table for OR Truth table for NOT
P Q P&& P Q P||Q P Not P
Q
T T T T T T T F
T F F T F T F T
F T F F T T
F F F F F F

Ex: if (age>30 && salary>15000)


If(number<0 || number>100)

4. Assignment operators: Assignment operators are used to assign the result of an


expression to a variable. v op = exp;

Operator Examples Meaning


+= a+=1 a=a+1
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a+b
%= a%=b a=a%b
5. Increment / Decrement operator: ( ++ /--)
The increment operator is a unary operator. It is used to increase the value of an operand by
1.
The decrement operator is a unary operator. It is used to decrease the value of an operand by
1.

25
UNIT-I

The increment operator '++' and decrement operator ‘- -‘has different meaning depending
on the position it is used. It means this operator is used again two ways. They are pre-
increment, post-increment and pre-decrement, post-decrement.

Pre-increment: ++m; Post-increment: m++;


Pre-decrement: --m; Post-decrement: m--;

Example:
#include<stdio.h>
#include<conio.h>
main()
{
int a=1,b=2;
printf(" \n Post increment of a is %d ",a++);
printf(" \n post decrement of b is %d ",b--);
printf(" \n pre increment of a is %d ",++a);
printf(" \n pre decrement of b is %d ",--b);
getch();
}

6. Conditional operators:
It is also known as Ternary Operator. The general form of conditional operator is as
follows:
Syntax: (Exp1)? Exp2: Exp3;
Working: Exp1 is evaluated first, if it is true Exp2 will be executed. If Exp1 is false Exp3
will be executed.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int a=120, b=23;
(a>b)? printf("hi"):printf("hello");
getch();
}

7. Bitwise Operators: C supports special operators known as bitwise operators for


manipulation of data at bit level. These operators are used for testing bits or shifting
them to right or left. Bitwise operators may not be applied to float or double data type.

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR (Exclusive OR)
~ 1’s complement
>> Right shift
<< Left shift

26
UNIT-I

P Q P&Q P Q P|Q P Q P^Q


1 1 1 1 1 1 1 1 0
1 0 0 1 0 1 1 0 1
0 1 0 0 1 1 0 1 1
0 0 0 0 0 0 0 0 0

Left shift Right shift


P ~P A 0100101 A 0100101
1 0 A<<3 0101000 A>>3 0000100
0 1 A<<5 0100000 A>>5 0000001

8. Special operators:
The following are the special operators used in ‘C’ language.
 Comma operator (,)
 Sizeof operator : This operator returns the size of an operand
 Pointer operator ( & and *)
 Member selection operators (. And ->)
The sizeof Operator:
The sizeof is a compile time operator and, when used with an operand, it returns the number
of bytes the operand occupies. The operand may be a variable, a constant or a data type
qualifier.
Examples: m=sizeof(sum);
n=sizeof(int);

TYPE CONVERSION
Type conversion in C can be classified into the following two types:
1. Implicit type conversion.
2. Explicit type conversion.
When the type conversion is performed automatically by the compiler without programmer’s
intervention, such type of conversion is known as implicit type conversion or type
promotion.
The compiler converts all operands into the data type of the largest operand.

The type conversion performed by the programmer by posing the data type of the expression
of specific type is known as explicit type conversion.
The explicit type conversion is also known as type casting.
Type casting in c is done in the following form:
(data_type)expression;

Typecasting: When a value is converted from one data type to another data type then it is
called type casting.

Syntax: (data type) expression


Example:
#include<stdio.h>
main ()
{

27
UNIT-I

int a=25;
float x, y;
x = a/ 4;
y = (float) a /4;
printf("x = %f',x);
printf(''y = %f' ,y);
}
Output:
X=6.0000
Y=6.25000

28

You might also like