C Program

You might also like

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

5.

Programming Concept and Logics


5.1. Programming Language
• A language is a means of communication. A programming language is well defined set
of rules for specifying program sequence of instructions.
• A programming language consists of symbols, characters and rules that permit people to
communicate with computers.
• A programming language either use for special purpose (controlling a robot) or general
purpose.
• There are five generation of programming language. They are
1. Machine Level Language / First Generation Language
2. Assembly Level Language / Second –Generation language
3. Procedural Orient Language / Third Generation Language
4. Problem Oriented Language / Fourth-Generation Language
5. Natural Language / Fifth-Generation Language
5.1.1 Machine Level Language
• The machine-level language is a language that consists of a set of instructions that are in
the binary form 0 or 1.
• As we know that computers can understand only machine instructions, which are in
binary digits, i.e., 0 and 1, so the instructions given to the computer can be only in binary
codes.
• Creating a program in a machine-level language is a very difficult task as it is not easy
for the programmers to write the program in machine instructions.
• It is error-prone as it is not easy to understand, and its maintenance is also very high. A
machine-level language is not portable as each computer has its machine instructions, so
if we write a program in one computer will no longer be valid in another computer.
5.1.2. Assembly Level Language
• The assembly language contains some human-readable commands such as mov, add, sub,
etc. The problems which we were facing in machine-level language are reduced to some
extent by using an extended form of machine-level language known as assembly
language. Since assembly language instructions are written in English words or
abbreviations like mov, add, sub called mnemonics, so it is easier to write and
understand.
• As we know that computers can only understand the machine-level instructions, so we
require a translator that converts the assembly code into machine code. The translator
used for translating the code is known as an assembler.
• The assembly language code is not portable because the data is stored in computer
registers, and the computer has to know the different sets of registers.
5.1.3. High Level Language
• The high-level language is a programming language that allows a programmer to write
the programs which are independent of a particular type of computer.
• The high-level languages are considered as high-level because they are closer to human
languages than machine-level languages.
• It is more or less independent of the particular type of computer used (i.e. more portable)
and has its own set of rules called syntax. Its main advantage is that it is easier to read,
write and maintain.
• The first high level programming languages were designed in the 1950s. Now there are
dozens of such languages available such as BASIC, COBOL, C, C++, FORTRAN, LISP,
PASCAL, prolog, etc.
• This language is lot slower in terms of execution as compared to low level language.
Compiler or interpreter is used to convert high level language to machine language.
• There are two types of high-level language. They are
a. Procedure-oriented language
b. Problem-oriented language
a. Procedure Orient Language
• Procedural programming is based upon the idea of series of procedure calls. A
programmer writing program in this language can exactly specify a sequence of
steps in order to perform a particular task.
• Languages which express step-by-step algorithms written to solve a problem are
known as procedural languages. A procedure may be a program in itself that may
be called within a main program, a subroutine or another program.
• A programmer knows exactly what is to be accomplished at the end of the
program and uses a sequence of algorithmic steps in order to achieve it. C
language is example of procedure-oriented programming language.
• Advantages
i. Statements are similar to English and easy to understand
ii. Less time consuming to develop program
iii. Easy to find syntax error and debug.
iv. Standardized and machine independent.
b. Problem Orient Language
• The language which is application specific and used to solve specific problems is
called problem-oriented language. For example, SQL for database, HTML and
PHP for world wide web content, Postscript page description language for
printers.
• Problem oriented language is also called fourth generation language or 4GL and it
is closer to natural language.
• They do not need step by step instruction. One just describes what he wants from
the program and get the result.
• Application software like PowerPoint, word processors, spreadsheets and query
language like SQL, PLUS, DATATRIEVE, etc are some example of problem
oriented language.
• Advantages
i. Standardized, machine independent and can run any program on any
machine.
ii. Varieties of language are available.
iii. Easy to find error and debug.
iv. Use of standard maths symbol (eg +, =, *, / etc)
v. Coding is Faster and easier.
5.2 Translator
• A translator is a program that translate the program written in assembly or high level
language (source code) to machine language (object code).
• Different language translator are
1. Assembler: It is a translator that converts code of assembly language into
machine language. In assembly language, computer has to run assembler, first it
translates the assembly language into the machine language, and then execute the
object code to get result.
2. Compiler: A compiler is a translator which translates a high-level program
(Source code) into machine instruction at once. In compiler, syntax error is
detected after the compilation of complete program. This complete translation
process is called compilation.
3. Interpreter: An interpreter is a translator which translates high level language
into a machine level language, one line at a time and executes line of the program
after it has been translated. In interpreter, syntax errors can be trapped before
translation of every line.
4. Linker: Linker is also known as editor or binder. In many high-level languages,
we can write different pieces of programs called modules. These pieces of
modules must be combined to form a complete executable program. Linker is a
program that combines object modules to convert the program into an executable
program.
5.3. Concept of Programming Statements
• A computer program statement is an instruction for the computer program to perform an
action.
• There are many different types of statements that can be given in a computer program in
order to direct the actions the program performs or to control the order that the actions are
carried out in. The action can be declaring variable, assigning values, looping, branching,
etc.
• A program statement tells the computer to do something. This may be as simple as
adding two numbers together or as complex as connecting to a server across the Internet.
• A statement consists of single line of code called simple statement or a series of
statement in a block called compound statement. The statement is also known as
expression as well as sentence in English.
• For Example
1. Simple Statement
• Assignment Statement: A = 5
• Increment Statement: ++i, i++
2. Compound statement
{ L = 5;
B = 8;
Perimeter_of_rectangle = 2*(L+B);
Area_of_rectangle = L*B;
}
5.4. Error in Programming Language
• Debugging is a process of detecting, locating, and errors in a program. Mistakes may be
syntax error and semantics error.
1. Syntax Error: Syntax error arises due to grammatical error or in writing format.
This error is detected by translator during translation so, it is easier to correct.
2. Semantics Error: A semantic error occurs when a statement is syntactically
valid, but does not do what the programmer intended. Sometimes these will cause
your program to crash, such as in the case of division by zero. The different types
of semantics error are discussed below.
a. Logical Error: Logical error arises due to conceptual or logical mistake in
the program. The program will be executed and will produced output but
the output will not be accurate.
b. Run Time Error: Run time error is detected only while running the
program. The program can be compiled and run, but the result is
erroneous. This error arises due to mismatch of data types (eg use of
integer instead of float), not enough memory to run the program.
5.5. Program Control Structure
• The breaking down of a large program into simple, easily understandable smaller
modules in a hierarchical order using top-down approach is called structured
programming.
• In structured programming, every program modules has one entry and exit point and this
makes the program run in logical sequence order. It avoids the indiscriminate use of
control statements.
• Structured program can be constructed using three fundamental control structures. They
are
• Sequence: A sequence is simply a series of procedure that follow one another.
• Selection: The selection involves a choice. It offer two or more paths to follow at
a point in the program where a decision must be made.
• Iteration: Iteration is an operation that repats until a certain condition is met.
• Diagram of hierarchical structure:

1. Sequential Structure
• Sequential structure refers to line by line execution of statements in the same
order they appear. It is also known as straight line structure.
• It doesn’t have any jump, branch or looping statements.
• The flow of control passes from one statement to next in sequence. By which that
the control flows in straight line executing one statement to another sequentially
from top to down and left to right.
• For example
START
LOAD A
LOAD B
SUM A, B
STORE SUM
END
2. Selection or Branching Structure
• Selection is a two-way branching structure because the flow of control follows
either one of two paths.
• The control first tests the condition and makes decision. If the condition is “true”
or satisfied, then it follows the “true” path statement and if the condition doesn’t
satisfy, then if follows the “false” path statement.
• So, the selection is a method of selecting one of two or more paths of
computations. The decision can be based on comparison of two variables or sign
of two variables etc.
• The selection structure is similar to IF-THEN-ELSE statements as shown below.
IF percentage >= 60
THEN
Division = “first”
ELSE
Division = “second”
3. Iteration or Looping Structure
• Looping is a programming structure that repeats a sequence of instructions until a
specific condition is met.
• A loop is a statement that repeats over and over, while a certain condition is true.
Or, to state it another way, it runs until a condition is false.
• There are two types of loops.
1. If the operation is repeated for a fixed number of times, then the loop is
called ‘fixed loop’. In fixed loop, the values of the variable inside the loop
do not have any effect on the number of iterations.
2. The second loop is called ‘variable loop’ in which the operations are
repeated until a specific condition met. In ‘variable loop’ the number of
iterations may vary. For example, searching a number within a group of
number organized randomly.
• FOR, WHILE, DO-WHILE are some examples of looping structure. For example
WHILE (Percentage >= 80)
Distinction = Distinction + 1
ENDWHILE
5.6. Programming Design Tools
 Computers are problem solving devices and it is an electronic programmable machine
that requires a set of instructions to perform tasks. To facilitate a computer to solve
problems effectively, clear and concise instructions must be provided to it. So, program
design tools are tool used to developed program.
 Program development follows almost the same step for any problem-solving tasks. There
are five major steps in the process of program development. They are
1. Defining Problem: It involves the problem analysis, and specifying the input,
process and output required.
2. Planning the Solution: In this phase computer related work begins. It is a
structure or detail design phase. We plan the solution to the given problem using
standard program development tools. Program development tools helps to
visualize what the program is going to do and how it is going to do.
3. Coding the Program: Once the design has been developed and reviewed, the
next step is the actual writing of the program called coding. Coding is the process
of translation from a detailed design to program statements in a programming
language.
4. Testing/modifying The Program: Testing is the process of evaluating a newly
developed program to check if it generates desired output or not.
5. Documentation the Program: Documentation is the process of collecting,
storing and maintaining a complete record of system and other documents used or
prepared during the different phase of the life cycle of system.
 There are many types of program design tools. Some of them are algorithm, flowchart
and pseudo code.
1. Algorithm
1. An algorithm is the step wise logical instructions written in any human
understandable language to solve particular problem in a finite amount of time. It
is written in simple English language.
2. General features of an algorithm
• Includes clear specification of input.
• Uses internal variables
• Provide clear prior specification of program steps.
• Use ‘goto’ to transfer the control to a step other than next.
• Use conditional (if… then… else) and looping (bounded loops, while and
until loops).
• Use of subroutines to perform subtasks.
• Use termination condition.
3. Algorithm to add 3 numbers and print their sum:
• START
• Declare 3 integer variables num1, num2 and num3.
• Declare an integer variable sum to store the resultant sum of the 3
numbers.
• Print the value of variable sum
• END
4. Write an algorithm to calculate simple interest
• Step 1: Start
• Step 2: Read Principal Amount, Rate and Time
• Step 3: Calculate Interest using formula SI= ((amount*rate*time)/100)
• Step 4: Print Simple Interest
• Step 5: Stop
 Characteristics of an algorithm
1. Finiteness: An algorithm should use finite number of logical steps and
termination after executing those steps.
2. Definiteness: Each step must be defined precisely and unambiguously and must
be self-explanatory.
3. Input: An algorithm must have zero, one or more legal or valid input sets.
4. Output: An algorithm must have one or more outputs as a function of input and
process.
5. Effectiveness: Every step should be executed exactly and in finite time and give
the desire results.
6. Design Aid: An algorithm is a basis for developing the flowchart and helps
designing the solution effectively and efficiently.
7. No standard format or syntax
8. Language independent
2. Flowchart
 A flowchart is simply a graphical representation of steps. It shows steps in sequential
order and is widely used in presenting the flow of algorithms, workflow or processes.
Typically, a flowchart shows the steps as boxes of various kinds, and their order by
connecting them with arrows.
 Flowchart facilitates the communication between the programmer and business
people.
 Flowchart plays a vital role in programming and quite helpful in understanding the
logic of complicated and lengthy problems.
 Once the flowchart is drawn, it is easy to write the program in any high level
language.
 Different flowchart shapes have different conventional meanings. The meanings of
some of the more common shapes are as follows:

Start Input/Output

Process Document

Connector
Decision Line
 Draw a flowchart to add two numbers.

 Draw a flowchart to find average of three numbers

3. Pseudo Code or Structured English


• Pseudo means not a true program code, but is a code that gives some reflection of
guide line for actual coding.
• It uses logical constructions and imperative sentences to carry out instructions for
actions. The sentence is similar to simple sentence in English. Therefore, structure
English is the use of simple English language with the syntax of structured
programming.
• Elements of Structured English:
1. Operation Statements: It is written in English phrases and executed from
top to down approach. It is written in English statement such as add,
multiply, move etc.
2. Conditional Blocks: It uses keywords such as IF, THEN and ELSE
3. Repetition Blocks: It uses keywords such as DO, WHILE and UNTIL
• Guideline while writing the pseudo code
1. Statements should be clear and unambiguous.
2. Use one line per logical element.
3. All logic should be express in sequential, decision or repetition structure
blocks.
4. Logical blocks should be indented to show the relationship and hierarchy.
5. Keywords like IF, ELSE, THEN, SO, WHILE, LT, LE, TRUE, FALSE,
AND, OR, CREATE, DELETE, EXIT, UNTIL, END, REPEAT, BEGIN,
START, STOP, etc should be capitalized.
6. When the words or phrases have been defined in the Data Dictionary then
underline those words or phrases to indicate that they have a specialize
reserved meaning.
• Write a pseudo code to find the sum of two numbers
• START
• NUMBER a, b, sum
• OUTPUT(“Input first number”)
• INPUT a
• OUTPUT(“Input second number”)
• INPUT b
• s = a+b )
• OUTPUT(“Sum of two number is”, s)
• END
5.7. Codes
• Every type of data including number, text, image, audio and video are numbers (binary
number) for the computer. So, these data have to be converted into binary.
• Data representation codes are used to represent these data in the computer. Some of the
representation codes used for numbers and text are
1. Absolute Binary
2. BCD
3. EBCDIC
4. UNICODE
5. ASCII

1. Absolute Binary
• It can be used to represent only the numbers. In absolute binary the whole number
is converted to binary number. For example, 45 is represented as 101101.
• A code that is used to represent the digital data converted from analog data is
called gray code or absolute binary code.
2. BCD (Bi nary Coded Decimal)
• In the BCD code, 4 bits represent a decimal number. For example, 2 is
represented as 0010. If decimal number consists of more than 1 digit, then each
digit is represented individually by its 4-bit binary equivalent. For example, 123 is
represented as 0001 0010 0011.
3. EBCDIC
• EBCDIC stands for extended binary coded decimal interchange code. It is
extended version of BCD. 6-bit BCT cold represent only the alphabets and
numbers. It can’t represent all characters and symbols. EBCIDC uses 8-bits
representation. So, it can represent all characters and symbols of the English. The
8 bits are divided into zone bit (first 4 bits) and digit (last 4 bits).
• For example, A is represented as 1100 0001, X as 1110 0111, + as 0100 0000, =
as 0111 1110, etc.
4. ASCII
• ASCII stands for American Standard Code for Information Interchange. It is used
to represent all the uppercase and lowercase, alphabets, numbers, punctuation
mark, and special symbols. Initially, it is used as 7-bit code but later it is modified
to 8-bit code. 8-bit ASCII can represent 256 characters.
• For example, C is represented as 01000011, was 01010111, $ as 00100100, etc.
5. Unicode
• The Unicode worldwide character standard uses 4 bytes i.e. 32 bits to represent
each letter, number and symbol. It can be used to represent more than 4 billions
(4,294,967,296) different characters and symbols. It is unique for every language
characters and symbols such as Devanagari, Newari, Maithali, Japanese, Russian,
etc.
• One major advantage of Unicode is that it is compatibility with ASCII code.

5.8.1. Introduction to C
• C programming is a general-purpose, procedural, imperative computer programming
language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to
develop the UNIX operating system.
• C is the most widely used computer language.
5.8.2. Why to learn C?
• C programming language is a MUST for students and working professionals to become
a great Software Engineer specially when they are working in Software .
• some of the key advantages of learning C Programming:
1. Easy to learn
2. Structured language
3. It produces efficient programs
4. It can handle low-level activities
5. It can be compiled on a variety of computer platforms
5.8.3. Facts About C
• C was invented to write an operating system called UNIX.
• C is a successor of B language which was introduced around the early 1970s.
• The language was formalized in 1988 by the American National Standard Institute
(ANSI).
• The UNIX OS was totally written in C.
• Today C is the most widely used and popular System Programming Language.
• Most of the state-of-the-art software have been implemented using C.
5.8.4. Application of C Programming
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
5.8.5. Structure of C Program
• A program is a sequence of instruction. Instruction of C program is written as statement.
• A Statement is terminated by semicolon (;).
• One or more statements form a block (compound) statement enclosed within a pair of
braces, i.e.{}.
• Every C program consists of one or more functions and every C program must contain a
special function name main().
• Comment is written within the delimiters /* and */
HELLO WORLD EXAMPLE
• A C program basically consists of the following parts −
1. Preprocessor Commands
2. Functions
3. Variables
4. Statements & Expressions
5. Comments
• Let us look at a simple code that would print the words “Hello World“
#include <stdio.h>
#include <conio.h>
#include <math.h> sqrt(5,2); 5*5=25
int main(){
/* my first program in c */
printf(“hello world”);
return 0;
}
• Let us take a look at the various parts of the above program –
1. The first line of the program #include <stdio.h> is a preprocessor command,
which tells a C compiler to include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where the program execution begins.
3. The next line /*…*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program.
4. The next line printf(…) is another function available in C which causes the
message “Hello, World!” to be displayed on the screen.
5. The next line return 0; terminates the main() function and returns the value 0.
5.8.6. Compiling Process
1. Editor
• In general, an editor refers to any program capable of editing files. Good
examples are image editors, such as Notepad, WordPad, etc.
• The term editor is commonly used to refer to a text editor, which is a software
program that allows users to create or manipulate plain text computer files. They
are often used in the field of computer programming.
• Notepad and WordPad - Microsoft Windows included text editors
• TextEdit - Apple computer text editor
• Word - Word processor for Windows and Apple computers
• Microsoft Edit - MS-DOS text editor
• Notepad++ - Our favourite free text editor, Notepad++ is a powerful alternative
to Windows Notepad
2. Preprocessor
• In computer science, a preprocessor is a program that processes its input data to
produce output that is used as input to another program.
• The most common example of this is the C preprocessor, which takes lines
beginning with '#' as directives.
3. Compiler
• Compiler is a computer program that translates computer code written in
one programming language (the source language) into another language
(the target language).
• The name "compiler" is primarily used for programs that translate source
code from a high-level programming language to a lower level
language (e.g., assembly language, object code, or machine code) to create
an executable program.
• Compiler translates the pre-processed source code into machine language that
consists of sequence of 0s and 1s.
• If compiler find any error, the compilation may continue in order to detect further
error but computer won’t produce any compiled program. If it does not find any
error, then it produce object code
4. Linker
• A linker or link editor is a computer system program that takes one or
more object files (generated by a compiler or an assembler) and combines them
into a single executable file, library file, or another "object" file.
• Linkers can take objects from a collection called a library
• In case of C, the standard input and output function are contained in library file
stdio.h, so most basic program will require a library function. After compilation
of the program files, computer must somehow link these separate pieces to form
executable program. The linking is done by linker. The executable file will have
extension .exe.
5. Executable file
• The text editor produces .c source files, compiler converts this .c file to .obj
object file, linker produces .exe (executable file) from .obj file.
• We can then run .exe files as an application to generate simply output by typing
their names at the DOS prompt or run using windows menu.
• Many compilers provide the programmer with debugging tools, such as
displaying informative error messages indicating the source of many of the errors,
colored-coded source code, etc.
5.8.7. C Preprocessor and Header Files
• C preprocessor is often known as a macro processor and used automatically by the C
compiler to transform the program before compilation.
• All preprocessor commands begin with a hash symbol (#).
• It is called a macro processor because it allows us to define macros, which are brief
abbreviations for longer constructs. For example
• #define PRINT(x) printf(“#x = %d”, (x) )
• #define SQR(x) ( (x) * (x) )
• #define CUBE ( (x)*(x)*(x) )
• #define PER_CENT(x, y) ( (x) * 100.0 /(y) )
• Header file define certain values, symbols and operations which is included in the file to
obtain access to its contents. The header file has suffix .h.
• It contain only prototype of the function in the corresponding source file. For e.g., stdio.h
contain the prototype for printf while the corresponding source file contains its
definition.
• It saves time for writing and debugging the code.
5.8.8. Character Set Used in C
• A character set in C contains any alphabet, digit or special symbol used to represent
information.
• The following table shows the valid alphabets, numbers and special character allowed in
C.

Alphabets A to Z, a to z and _(underscore)

Digits 0 to 9

Special Symbols !,@,#,$,%,^,^,&,<,>?,/;,:,” “,’ ‘,


5.8.9. Use Of Comment
• A comment is a text in the program, which won’t be compiled or executed. It is good to put
comment because it will be helpful to debug the program in future.
• Single line comment: Single line comment means we can give comment on a single line.
For example: //This is comment section. Comment what you want
• Multiple line comment: A multiple line comment means the programmer can give
comments for the multiple line.
For example: /* This is comment section.
Comment what you want */
5.8.10. C Tokens
• C Tokens are the smallest building block or smallest unit of a C program.
• The compiler breaks a program into the smallest possible units and proceeds to the various
stages of the compilation, which is called token.
• C tokens includes:
1. Identifiers
2. Keywords
3. Constants
4. Strings
5. Operators
6. Special Symbols
5.8.11. Identifiers
• Identifiers are user-defined names of variables, functions and arrays. It comprises of
combination of letters and digits. In C Programming, while declaring identifiers, certain rules
have to be followed viz.
1. It must begin with an alphabet or an underscore and not digits.var_123
2. It must contain only alphabets, digits or underscore. @!#$%&
3. A keyword cannot be used as an identifier
4. Must not contain white space.
5. Only first 31 characters are significant.
6. It is case sensitive. Int abc, ABC
Incorrect Identifier Correct Identifier

1count count1

hi!there hi_there

high…level high_level

Roll no Roll_no or Rollno

S.I. SI or S_I

5.8.12. Keywords
• Keywords is a reserved word that has standard and predefined meanings in C.
• Keywords are special words in C programming which have their own predefined meaning.
The functions and meanings of these words cannot be altered.
• Some keywords in C Programming are:

auto break case char

continue const do default

double else enum extern

for float go if

int long register return

sign static sizeof short

struct switch typedef union

void volatile while unsigned


5.8.13. Data Types in C
• A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
• Any variable used in the program must be declared before using it. It determines the way a
computer organizes data in memory. It determines how much space it occupies in storage and
how the bit pattern stored is interpreted.
• Different data types are discussed below.
1. int
• Integers are whole numbers that can have both zero, positive and negative values but
no decimal values. For example, 0, -5, 10
• We can use int for declaring an integer variable. i.e. int a;
2. Float
• float is used to hold real numbers. For example, float salary.
• In C, floating-point numbers can also be represented in exponential.
• For example, float normalizationFactor = 22.442e2
3. char
• Keyword char is used for declaring character type variables. For example char test =
'h’;
• char represents single alphabet or symbol or multiple alphabets or symbols for the
string.
4. void
• The void data type has no values. It is used as return type for functions that do not
return a value.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767


signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to


2,147,483,647

signed long int 4 byte -2,147,483,648 to


2,147,483,647

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

float 4 byte

double 8 byte

long double 10 byte

5.8.14. Constants and Variables


Constant
• A constant is a quantity that doesn’t change during program execution. Constant refer to
fixed values that may not be altered by the program.
• C has basic four types of constants. They are
1. Integer Constant
2. Floating point constant
3. Character Constant
4. String Constant #define a=20000perimeter of rectangle = a*(l+b);
1. Integer Constant
• An integer constant is integer valued number. It consists of a sequence of digits.
• The method of writing integer constants has been specified in the following rule.
1. An integer constant must have at least one digit and must not contain any
decimal point.
2. It may contain either +ve or –ve sign. A number with no sign is assumed to be
positive.
3. Commas cannot appear in an integer constant.
2. Floating Point Constant
• They are also known as real constants. A real constant contains a decimal point or an
exponent. It can be either +ve or -ve.
• Commas and blank space are not allowed within a real constant.
• Examples: – 254.175, -16.47 -0.5e-7 +4.1e8
3. Character Constant
• A character constant is a character which is enclosed in single quotes. A character
constant is of size 1byte and can contain only 1 character.
• A character can be an alphabet like a,b,A,C etc or a special character like &,^, $, #,@
etc or a single digit from 0 through 9. It can also be an escape sequence character like
space ‘ ‘ or a null character ‘\o’ or a new line ‘\n’ etc.
• Example: ‘A’ ‘a’ ‘ b’ ‘8’ ‘#’ etc.
4. String Constant
• A string constant is a collection of characters enclosed in double quotations “”
• It may contain alphabets, digits, special characters and blank space.
• Example: “Circuits Today123”
Variable
• A variable is nothing but a name given to a storage area that our programs can manipulate.
• Each variable in C has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations
that can be applied to the variable.
Rules to name a Variable
1. Variable name must not start with a digit.
2. Variable name can consist of alphabets, digits and special symbols like
underscore _.
3. Blank or spaces are not allowed in variable name.
4. Keywords are not allowed as variable name.
5. Upper and lower case names are treated as different, as C is case-sensitive, so it is
suggested to keep the variable names in lower case.
Declaring, Defining and Initializing a variable
• Declaration of variables must be done before they are used in the program.
• Declaration does the following things.
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. Until the variable is defined the compiler doesn't have to worry about allocating
memory space to the variable.
4. Declaration is more like informing the compiler that there exist a variable with
following datatype which is used in the program.
5. A variable is declared using the extern keyword, outside the main() function.
• Defining a variable means the compiler has to now assign a storage to the variable
because it will be used in the program.
• Initializing a variable means to provide it with a value. A variable can be initialized and
defined in a single statement, like:
Int a = 20;

5.8.15. Specifier
• The basic data type can have various specifiers preceding them. A type of specifier alters the
meaning of the data type to more precisely fit a specific need.
• The four specifiers are signed, unsigned, long and short.
• The data types int can be modified as signed, unsigned, short and long. The char can be
modified as unsigned and signed. The float can be modified as double or long double.
5.8.16. Statement
• A statement consists of single line of code called simple statement or a series of statement in
a block called compound statement. The statement is also known as expression as well as
sentence in English.
• For Example
1. Simple Statement
• printf(“value of x is %d”,x);
2. Compound statement
{
int l,b,Area_of_rectangle;
Area_of_rectangle = l*b;
printf(“Area of rectangle is %d”, Area_of_rectangle);
}
Escape Sequences
• Escape sequences are used in the programming languages C . An escape sequence is a
sequence of characters that does not represent itself when used inside a character or
string literal, but is translated into another character or a sequence of characters that may be
difficult or impossible to represent directly.
• In C, all escape sequences consist of two or more characters, the first of which is the
backslash, \ (called the "Escape character"); the remaining characters determine the
interpretation of the escape sequence.
• Some common escapes sequences are listed below.
1. \n : New Line
2. \t : Horizontal Tab
3. \r : Line Feed or Carriage Return (Takes the cursor to the beginning of line in which
it is currently placed)
4. \f : Form Feed
5. \b : Move cursor one position the left of its current position
6. \" : Double Quote
7. \\ : Display Backslash
8. \a : Alert (It alerts by sounding the speaker inside computer)
9. \0 : It represents NULL character
5.8.17. Operator and Expressions
Operator
 An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Conditional Operator
• Bitwise Operator
• Special Operator
1. Arithmetic Operator
 Arithmetic operator is a symbol used for basic mathematical calculations.
 The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20, then −

 Example
Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from A − B = -10


the first.

* Multiplies both operands. A * B = 200

/ Divides numerator by de- B/A=2


numerator.

% Modulus Operator and B%A=0


remainder of after an integer
division.

++ Increment operator increases the A++ = 11


integer value by one.

-- Decrement operator decreases A-- = 9


the integer value by one.

2. Relational operator
 Relational operator is a symbol that determines the relationship between two different
operands.
 The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then

• Examples
Operator Description Example

== Checks if the values of two operands are (A == B) is not true.


equal or not. If yes, then the condition
becomes true.

!= Checks if the values of two operands are (A != B) is true.


equal or not. If the values are not equal,
then the condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right operand. If
yes, then the condition becomes true.

< Checks if the value of left operand is less (A < B) is true.


than the value of right operand. If yes,
then the condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of right
operand. If yes, then the condition
becomes true.

<= Checks if the value of left operand is less (A <= B) is true.


than or equal to the value of right operand.
If yes, then the condition becomes true.

3. Logical Operator
 Logical operator is a symbol that logically connects the logical expression i.e. it is used to
connect two or more expressions.
 Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then –
 Examples

Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then the condition
becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands is non-zero, then the condition
becomes true.

! Called Logical NOT Operator. It is used to !(A && B) is true.


reverse the logical state of its operand. If a
condition is true, then Logical NOT operator
will make it false.

4. Assignment Operator
• Assignment operator is a symbol to assign value or a result of an expression to an identifier.
• Syntax, identifier = expression. Example x = 10; y = a+b;
• C also allows multiple assignment statement using =, for example, int a=b=3;
• The following table lists the assignment operators supported by the C language

Operator Description Example

= Simple assignment operator. Assigns values from C = A + B will assign the value of A
right side operands to left side operand + B to C

+= Add AND assignment operator. It adds the right


operand to the left operand and assign the result to C += A is equivalent to C = C + A
the left operand.

-= Subtract AND assignment operator. It subtracts the


right operand from the left operand and assigns the C -= A is equivalent to C = C - A
result to the left operand.

*= Multiply AND assignment operator. It multiplies the


right operand with the left operand and assigns the C *= A is equivalent to C = C * A
result to the left operand.

/= Divide AND assignment operator. It divides the left


operand with the right operand and assigns the result C /= A is equivalent to C = C / A
to the left operand.

%= Modulus AND assignment operator. It takes


modulus using two operands and assigns the result C %= A is equivalent to C = C % A
to the left operand.
5. Bitwise Operator
• Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |,
and ^ is as follows

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows:


A = 0011 1100 A<<3 A>>2 0000 1111 1111 0000
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
• The following table lists the bitwise operators supported by C. Assume variable 'A' holds
60 and variable 'B' holds 13, then

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both (A & B)
operands. = 12,
i.e.,
0000
1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B)


= 61,
i.e.,
0011
1101

^ Binary XOR Operator copies the bit if it is set in one operand but (A ^ B)
not both. = 49,
i.e.,
0011
0001

~ (~A ) =
Binary One's Complement Operator is unary and has the effect of ~(60),
'flipping' bits. i.e,. -
0111101

<< Binary Left Shift Operator. The left operands value is moved left A << 2
by the number of bits specified by the right operand. = 240
i.e.,
1111
0000

>> Binary Right Shift Operator. The left operands value is moved A >> 2
right by the number of bits specified by the right operand. = 15 i.e.,
0000
1111
6. Special Operator
• The following table lists the bitwise operators supported by C.

Operators Description

This is used to get the address of the


& (Address Operator) variable.
Example: &a will give address of a.

This is used as pointer to a variable.


*(Pointer Operater) Example: * a where, * is pointer to the
variable a.

This gives the size of the variable.


Sizeof ()
Example: size of (char) will give us 1.

It allows us to put multiple expressions in


, (Comma Operator)
the same statement, separated by comma.

Operators Precedence and Associatively


• Operator precedence determines which operator is performed first in an expression with
more than one operators with different precedence.
• Operators Associativity is used when two operators of same precedence appear in an
expression. Associativity can be either Left to Right or Right to Left.
Associativity
Precedence Operator Operator Category

Parentheses (function call) left-to-right


()
Brackets (array subscript)
[]
1. Member selection via object
.
name
->
Member selection via pointer

right-to-left
Prefix increment/decrement
Unary plus/minus
++ —
Logical negation/bitwise
+–
complement
!~
Cast (convert value to
2. (type)
temporary value of type)
*
Dereference
&
Address (of operand)
sizeof
Determine size in bytes on this
implementation

left-to-right
3. * / % Multiplication/division/modulus

left-to-right
4 + – Addition/subtraction

left-to-right
5 << >> Bitwise shift left, Bitwise shift right

< <= Relational less than/less than or equal left-to-right


6
> >= to
Relational greater than/greater than or
equal to

left-to-right
7 == != Relational is equal to/is not equal to

left-to-right
8 & Bitwise AND

left-to-right
9 ^ Bitwise exclusive OR

left-to-right
10 | Bitwise inclusive OR

left-to-right
11 && Logical AND

left-to-right
12 || Logical OR

right-to-left
13 ?: Ternary conditional

Assignment right-to-left
=
Addition/subtraction assignment
+= -=
Multiplication/division assignment
*= /=
14 Modulus/bitwise AND assignment
%= &=
Bitwise exclusive/inclusive OR
^= |=
assignment
<<= >>=
Bitwise shift left/right assignment
left-to-right
15 , Comma (separate expressions)

Expressions
• An expression is a formula in which operands are linked to each other by the use of
operators to compute a value. An operand can be a function reference, a variable, an array
element or a constant.
• For Example, c = a+b
In the above expression, plus character (+) and assignment (=) are an operator, and a, b
and c are the three operands.
• There are four types of expressions exist in C:
1. Arithmetic expressions
2. Relational expressions
3. Logical expressions
4. Conditional expressions
• Each type of expression takes certain types of operands and uses a specific set of
operators. Evaluation of a particular expression produces a specific value.
5.8.18. Typecasting and Conversion
• Typecasting is converting one data type into another one. It is also called as data
conversion or type conversion.
• 'C' programming provides two types of typecasting operations. They are
1. Implicit
2. Explicit
1. Implicit int x =10; float b; b = x, 10.0000
• Implicit type casting means conversion of data types without losing its original
meaning. This type of typecasting is essential when you want to change data
types without changing the significance of the values stored inside the variable.
• This type of conversion is done automatically by the compiler itself.
2. Explicit
• 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.
• Syntax, (data_type) expression; b = (float) x
C Program to Illustrate Typecasting and Conversion
#include<stdio.h>
int main(){
float x;
int num, den;
printf("Enter the value of numerator and denumerator");
scanf(“ %d %d”, &num, &den);
x = num/den
printf(“value of x by implicit conversion is %f”,x);
x = (float) num/ (float) den;
pintf(“value of x by explicit conversion is %f”, x);
return 0;
}
5.8.19. Introduction to Library Function
• Library functions are built-in functions that are grouped together and placed in a common
location called library.
• Each function here performs a specific operation. We can use this library functions to get
the pre-defined output.
• All C standard library functions are declared by using many header files. These library
functions are created at the time of designing the compilers.
• The prototype and data definitions of these functions are present in their respective
header files. To use these functions we need to include the header file in our program. For
example,
• If you want to use the printf() and scanf() functions, the header file <stdio.h> should be
included.
S.N. Function & Description

1 printf()
This function is used to print the all char, int, float, string etc., values onto the output
screen.

2 scanf()
This function is used to read data from keyboard.

3 getc()
It reads character from file.

4 gets()
It reads line from keyboard.

5 getchar()
It reads character from keyboard.

6 puts()
It writes line to o/p screen.

7 putchar()
It writes a character to screen.

8 fopen()
All file handling functions are defined in stdio.h header file.

9 fclose()
Closes an opened file.

10 getw()
Reads an integer from file.

11 putw()
Writes an integer to file.

12 fgetc()
Reads a character from file.

13 putc()
Writes a character to file.

14 fputc()
Writes a character to file.
15 fgets()
Reads string from a file, one line at a time.

16 f puts()
Writes string to a file.

17 feof()
Finds end of file.

18 fgetchar
Reads a character from keyboard.

19 fgetc()
Reads a character from file.

20 fprintf()
Writes formatted data to a file.

21 fscanf()
Reads formatted data from a file.

22 fputchar
Writes a character from keyboard.

23 fseek()
Moves file pointer to given location.

24 SEEK_SET
Moves file pointer at the beginning of the file.

25 SEEK_CUR
Moves file pointer at given location.

26 SEEK_END
Moves file pointer at the end of file.

27 ftell()
Gives current position of file pointer.

28 rewind()
Moves file pointer to the beginning of the file.

29 putc()
Writes a character to file.
30 sprint()
Writes formatted output to string.

31 sscanf()
Reads formatted input from a string.

32 remove()
Deletes a file.

33 flush()
Flushes a file.

5.8.20. Input/Output Functions


• Every C program performs three main functions i.e. it accepts data as input, processes
data and produces output.
• Input refers to accepting of data while output refers to the presentation of data. Normally
input is accepted from keyboard and output is displayed to screen.
• Input output operations are most common task in every programming language. C
languages has different type of input output functions for input-output operations.
• A program needs to read data in variable names: input operations. Also, data stored in
variables need to be displayed: output operation. C program does not define any keyword
to perform these input / output operations, it provides function such as getchar(),
putchar(), scanf(), printf(), gets(), puts(), getch(), putch().
Formatted Input / Output Functions
• Formatted input output functions accept or present the data in a particular format.
• The standard library consists of different functions that perform output and input
operations. Out of these functions, printf() and scanf() allow user to format input output
in desired format.
• printf() and scanf() can be used to read any type of data (integer, real number, character
etc.).
• Formatted input and output functions contain format specifier in their syntax and used to
store data more friendly.
• Syntax
printf(format-string, arg1, arg2,…….,argn);
scanf(format-string, arg1, arg2,…….,argn);
 Format conversion specifier controls the type and format of the value to be printed. Each
conversion specification begins with a % and ends with a conversion character.
 List of formatted conversions specifier are shown below
Specifier Meaning

%d / %i Signed decimal integer

%u Unsigned decimal integer

%c Unsigned char

%s String

%p Pointer in hexadecimal form

%o Unsigned octal integer

%x / %X Unsigned hexadecimal number

%e Floating point number in exponential format


in e notation

%E Floating point number in exponential format


in E notation

%f double number in decimal format

%g / %G double number in decimal format or


exponential format depending on the value
C Program Examples
// Program to find the square and cube of number
#include<stdio.h>
#include<math.h>

int main()
{
int n, s, c;
printf("Enter the number");
scanf("%d", &n);
s = pow(n,2);
c = n*n*n;
printf("Square of number is %f \nCube of number is %f",(float)s, (float)c);
return 0;
}
/*A
AB
ABC
ABCD
A B C D E */

#include<stdio.h>

int main()
{
printf("A");
printf("\nA\tB");
printf("\nA\tB\tC");
printf("\nA\tB\tC\tD");
printf("\nA\tB\tC\tD\tE");
return 0;
}
// program to find out remainder
#include<stdio.h>
int main()
{
int a, b, r;
printf("Enter the value of a and b");
scanf("%d %d",&a,&b);
r = a%b;
printf("The remainder of number is %d", r);
return 0;
}
//simple interest

#include<stdio.h>

int main()
{
float p, t, r,SI;
printf("Enter the principal amount:");
scanf("%f",&p);
printf("\nEnter the time in year:");
scanf("%f", &t);
printf("\nEnter the rate:");
scanf("%f",&r);
SI = p*t*r/100;
printf("\nSimple Interest amount:%f",SI);
return 0;
}
// Symbolic constant
#include<stdio.h>

#define PI 3.14

int main()
{
float r, area;
printf("Enter the radius of circle");
scanf("%f", &r);
area = 3.14*r*r; // literal constant
printf("\nArea of circle:%f",area);
return 0;
}
//Sum of n natural number
#include<stdio.h>
int main()
{
int n, sum = 0;
printf("Enter the value of n");
scanf("%d",&n);
sum = n*(n+1)/2;
printf("The sum of n natural number is %d",sum);
return 0;
}

You might also like