KEMBAR78
Unit - 2 Notes | PDF | Assembly Language | Operating System
0% found this document useful (0 votes)
58 views94 pages

Unit - 2 Notes

The document discusses the basics of C programming including problem formulation, problem solving, and programming languages. It covers defining problems, identifying logic, developing algorithms and code, testing programs, and strategies for problem solving like brute force, greedy algorithms, and divide-and-conquer approaches.

Uploaded by

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

Unit - 2 Notes

The document discusses the basics of C programming including problem formulation, problem solving, and programming languages. It covers defining problems, identifying logic, developing algorithms and code, testing programs, and strategies for problem solving like brute force, greedy algorithms, and divide-and-conquer approaches.

Uploaded by

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

2.

C PROGRAMMING BASICS

2.1 Problem Formulation

Problem formulation is an approach that allows the user to identify the problem, define the problem and find
solution to the problem in an organized way.

There are certain steps that should be followed in formulating the problem.

2.1.1 Problem Definition


Problem definition means defining the problem. A problem definition tells a programmer

 What is the problem?

 What task the program should perform?

 What will be the input?

 What should be the output ?

Example

Consider a problem, which is to find whether a number is odd/even.

So the programmer will need to identify the following

 The Problem is finding a number as odd/even.

 The program should exactly find any given number as odd/even.

 The input will be any integer value.

 The output should display text (odd/even.)

2.1.2 Identifying the Logic


Identifying the logic means identifying “how to solve the problem logically”. Some problem can be solved by
some mathematical formula and some problem requires logical formula. Only after finding the logic, the
programmer can further proceed to write the program. Some problem can be solved by using simple logic,
whereas some problem requires complex logical thinking.
Example

Consider the above odd/even problem.

In order to solve the odd/even problem we need to know what is an odd number and what is an even number.

Odd number is a number that is not divisible by 2.

Even number is number that is divisible by 2.

Now we need to know how to find whether a number is divisible or not.

When remainder is zero it is divisible

When remainder is Non-zero it is not divisible

Now we need to know how to find the remainder.

Modulus operator (%) gives the remainder of the number when divided by another number.

For example the value of 15%7 =1, because when 15 is divided by 7, the remainder is 1.

Now we identified the logic as

If Number %2 = 0, it is even number

If Number %2 = 1, it is odd number

2.1.3 Developing an Algorithm


An algorithm is sequence of steps. It clearly and sequentially explains, what are the operations to be performed
in order to solve the defined problem.

An algorithm can also be called as “rough program”. An algorithm is a previous step to a program. Once the
logic has been identified the algorithm can be developed easily. To develop algorithm the following steps
should be followed.

 Get the input.

 Convert the logic into sequential steps.

 Display the output.

Read find print


A A%2 Odd/Even
input process output

Example

For the above odd/even problem the algorithm can be written as

Step a - start

Step b - read a number a

Step c - find the remainder when a is divided by 2

Step d - if the remainder is zero, display even. Otherwise go to step e.

Step e - display odd.

Step f – End

2.1.4 Developing Code


The algorithm given can be easily understood by human beings but it cannot understand by machines. Machines
or computers can understand only machine language.

So first we need to convert the algortithm into a programming language code, for example a high level
programming language code such as C. Then we need to use system software such as compiler to convert the
high level language into machine level language.

The process of converting the algorithm into programming language is called as “developing code”.

For example the above algorithm can be converted into c as

int a;
if(a%2==0)
{
printf(“EVEN”);
}
else
{
printf(“ODD”);
}

2.1.5 Run/Execute the Program


Only after executing the code, we can get the output

2.1.6 Testing
Testing is the process of identifying the error/bugs in a program.

There are two main types of errors, syntax and logic error(s).

Syntax errors

Syntax errors are mistakes in syntax, spelling, or punctuation. A compiler will notify the syntax error, if any

In the above C program if you have typed “eles” instead of “else” then it is a syntax error.

Note: if you have a syntax error, the program will not execute.

Logic Errors

These are errors that make a program to produce unexpected results. These are more difficult to find. No
compiler will inform or notify about a logic error. The programmer only has to find the logic errors by
themselves.

In the above C program if you have typed “a%5” instead of “a%2” then it is a logical error.

Note: if you have a logical error, the program will execute but it will not give you the expected output.

2.2 Problem Solving

2.2.1 Introduction
Problem solving is a complicated process that needs in depth understanding of the problem ,ability to think
logically and careful planning. Problem solving means developing an algorithm that solves the problem. An
algorithm corresponds to a solution to a problem that is independent of any programming language.

Usually a program accepts the input ,manipulates the input according to the instructions and produces an
output, which is a solution to the given problem

2.2.2 A Framework for Problem Solving


The following four phases can be identified in the process of solving problems:

(1) Understanding the problem


(2) Making a plan of solution
(3) Carrying out the plan
(4) Verifying the solution

2.2.2.1 Understanding the Problem


If the problem is understood thoroughly, then it will be easier to obtain the solution. To understand the problem
,one should find out

 What is the problem definition?


 What are the inputs needed?
 What are the constraints and assumptions in the problem?
 What should be the expected output/result?

2.2.2.2 Making a plan of Solution


In order to make a plan for a solution ,we should find out

What do I know about the problem?

What is the information that I have to process in order the find the solution?

What does the solution look like?

What are the suitable ideas that will lead to the solution?

Whether the ideas can solve the problem?


2.2.2.3 Carrying out the Plan
It requires careful planning. It is the process of converting our idea into a model that will solve the problem. The
problem solving techniques such as pseudo code, flowchart and algorithm will be useful to carry out our plan
efficiently

2.2.2.4 Verifying the Solution


It is the process of testing our solution. we should check whether our idea solves the problem in all aspects.

2.2.3 Problem Solving Process


Analyze the problem

We should develop an Outline about the problem and its requirements. Then we should Design steps
(algorithm) to solve the problem

Implement the algorithm


We need to Implement the algorithm in any suitable programming and Verify that the algorithm works
properly and produces the expected results.

Maintenance

We should modify/update the program if the problem domain changes.

2.2.4 Problem Solving Strategies


Brute Force

Brute force is a straightforward approach to solve a problem. It is based on the problem’s statement and
definitions. It is considered as one of the easiest approach. It is useful for solving small instances of a problem.

Greedy Algorithms

It is also called as “take what you can get now" strategy.

The solution is constructed through a sequence of steps by choosing the best option available at each step.

Divide-and-Conquer /top down Technique

It is the process of splitting the problem into several smaller problems. Then each of these sub problems are
solved independently. Finally the solutions of the sub problems are combined to obtain a solution for the
original problem.

Top-down approach starts with the top level module and progresses downward to the lowest level module

Dynamic Programming/ Bottom-Up Technique

Dynamic Programming is a Bottom-Up Technique in which the smallest sub problems are explicitly solved
first and the results of these are used to construct solutions for larger sub-problems.

Bottom-up approach proceeds with the design of lowest level module or subsystem, to the highest module or
subsystem.

Transform-and-Conquer

These methods work as two-stage process. First, the problem is modified into form that will be suitable to
obtain the solution. In the second stage the problem is solved.

2.1 Introduction to Programming Language


2.1.1 Introduction
Program is set of instructions. Instructions are nothing but well formed statements that a computer can
understand.
 Programming is an art that makes a computer to understand our instruction and perform a task according
to our instruction.
There are three five main steps in a programming
1. Understand a problem.
2. Think of a solution.
3. Identify how to solve a problem.
4. Define instructions so that a computer can solve a problem.
5. Check if the computer solves the problem in all aspects.
2.1.2 Brief History of Programming Language
For doing programming we need a programming language. Without a language you cannot speak, similarly
without a programming language you cannot do programming. We human can understand languages like
English, Tamil etc, but a computer can understand only 0’s and 1’s i.e +ve and –ve voltage.
A human cannot understand 0’s and 1’s whereas a computer cannot understand human language like English
and Tamil. So how a human can communicate with computer or vice versa. This is where an operating system
comes into play.
Operating System is an interface between user and computer. It bridges the gap between the user and computer.
It converts 1’s and 0’s into human language or vice versa.

An Operating System is a computer program that manages the resources of a computer.

user user

kernel
os +
application

computer computer

OS = Kernel (Communicate with Hardware) + Application (Communicate with user)


Example :
Redhat (Application) + Linux (Kernel) = Redhat Linux (Open Source Operating System)
SUSE (Application) + Linux (Kernel) = SUSE Linux (Open Source Operating System)
Is Linux an Operating System? No, Linux in not an Operating System, it’s a kernel. There is nothing called
Linux operating system, there’s only Linux Based Operating System.
OS is a combination of Kernel and Application.
Kernel communicates with computer hardware whereas Applications communicate with user. Operating System
is a collection of program. It’s written by any other programming language like C, C++, Java, etc.
Kernel: A Kernel is a central component (Heart) of an operating system. It acts as an interface between the user
applications and the hardware.
Application: An application is a program or group of programs designed for end users to perform specific tasks.
Note: Most of the early operating system written by C. Example: Linux, Unix

Evolution of Programming Language


At earlier stage of computer, programming just meant working with 0’s and 1’s i.e. directly with the hardware.
For example working with switch (i.e. ON and OFF).

The above fig represents the evolution of programming language.

Machine/Low Language: (First Generation)


 Basic computer language is machine language and it directly communicates with machine without
human interaction.
 Programs in low-level languages are fast in execution. These languages are normally used to write
hardware programs.
 It is written in 0’s and 1’s and it is also called as computer’s naïve language.
 These programs are directly understood by a computer.
 It usually consists of two parts, OPCODE and OPERAND.
 The OPCODE instructs a computer “what tasks should be done”.
 The OPERAND tells a computer “where the data is located”
 The machine language instruction format would be
<OPCODE> <OPERAND>
(operation code) (memory location)
Example:
00011001 00001010

ADVANTAGES
 It is readily available in computer understandable form.
 No need for translation
 Since there is no need for conversion, it executes very fast

DISADVANTAGES
 Difficult to memorize the OPCODE
 Varies from machine to machine
 Not user-friendly
 Prone to errors
 Difficult and tedious to write.

Assembly Language: (Second Generation)


 Assembly language is used to write programs using the instruction set (collection of all possible
instructions) for a particular processor/controller.(example : 8051 or 8086 or MIPS).
 This language assigns a mnemonic code to each instructions so that it can be easily understood and used
by the human beings
 Each instruction (also called as mnemonics) does a specific task like addition subtraction etc.
Example: ADD  addition
SUB  subtraction
 Assembly Language requires an ASSEMBLER to convert the assembly code to machine level code,
because assembly language is not directly understood by the computer.
 The format of an assembly language is given below

[label] <opcode> <operands>


Example
BEGIN ADD A, B

ADVANTAGES
 Since numerical codes are replaced by mnemonics, it is easy to understand and use.
 Less error prone
 It occupies less memory space.
 It executes faster than high level

DISADVANTAGES
 It is difficult to memorize all the mnemonics
 Since different machines support different instructions set and hence different assembly language, there
is no standard assembly language.
 It takes more time to develop an assembly language
 It does not support modern software technologies

Procedure Oriented Language /High Level Language: (Third Generation)


 High-level languages are easy to learn by the user. High level programming languages are closer to
human language.
 It is similar as simple English language.
 High language consists of tokens such as keyword, identifier, constants and data types etc.
 A programmer need to understand these tokens and syntax(rules for writing these token) of a high level
language to write programs
 High Level Language requires a Compiler to convert it into ASSEMBLY language and then into a
machine level code.
 Few high level languages are C, C++, COBOL, and BASIC.
Example:
LET A =20
LET B =25
LET SUM = A + B
PRINT SUM

 High Level Language is Portable. To write assembly code it is necessary to know the architecture of the
processor or controller. To write a High Level Program it is not necessary to know the architecture
completely.
ADVANTAGES
 Since high level language is simple English, it is easy to understand and interpret without much effort.
 It is machine independent and not specific to any particular architecture. A high level language written
on one machine can run on any machine.
 Supports debugging and error handling with the help of debugger
DISADVANTAGES
 It does not directly communicate with hardware
 Computation time is more, since a program in a high level language needs to be converted into an
assembly language and then into machine language.

Fourth Generation Language (4GLs)


 4GLs are very closer to human language.
 Anyone can learn these languages without formal training.
 It follows a NON-PROCEDURAL approach i.e. it will specify only the needed output.
 A NON-PROCEDURAL approach will specify “what to do” and not “how to do”.
 4GLs developed by High level languages.
 Example of 4GLs is database queries, report generators and application generators.
Fifth Generation Language
 It is just an assumption how the future programming language should be.
 It should have the ability to process the natural language.
 In this kind of language, a user need not learn a programming language to instruct a computer.
 Just a gesture or voice of a user will give instructions to the computer.
2.4 Introduction to C Programming / Fundamentals
2.4.1 Introduction
 C programming is one of the thousands of computer programming languages that
allow users to create instructions for a computer to follow.
 The C High level programming language is a popular and widely used
programming language for creating computer programs. Without learning c you
cannot learn any programming language.
 Originally intended for writing system software, C was developed at AT & T’s Bell
Labs (USA) by Dennis Ritchie for the Unix Operating System (OS) in the early
1970s. Dennis Ritchie
2.4.2 Need for C
 C is simple and easy to learn and understand
 C is small because all you have to remember is 32 words(keywords)
 C is fast in execution. A small c program executes in approximately 0.031 seconds.
 You can do anything in C (right from simply printing a word to even an automated ticket reservation
system)
 C supports embedded system (Digital Camera, Microwave oven etc.).
Facts about C
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around 1970
 The language was formalized in 1988 by the American National Standard Institute (ANSI).
 The UNIX OS was totally written in C in the year 1973.
 Today C is the most widely used and popular System Programming Language.
 Today's most popular Linux OS and RBDMS MySQL has been written in C.
Application of C
C was initially used for system development work, in particular the programs that make-up the operating system.

Why use C?
1. Because it produces code that runs nearly as fast as code written in assembly language.
2. Because it supports all the features of high level language.
Since C connects the features of assembly language and the functionalities of high level language, it is also
called as middle level language.
C is used to develop :
 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Data Bases
 Language Interpreters
 Utilities
The following is a partial list of areas where C language is used:
 Embedded Systems
 Systems Programming
 Artificial Intelligence
 Industrial Automation
 Computer Graphics
 Space Research
 Image Processing
 Game Programming
2.4.3 Evolution of C
Where C Stands?
Computer Languages can be categorized two ways
1. Machine Oriented Languages (Ex-Assembly Languages)
2. Problem Oriented Languages (Ex-Basic, Fortran, Pascal)
Machine oriented languages have better machine efficiency and so called as Low Level Languages (LLL).
Problem oriented languages have better program efficiency and so called as High Level Languages (HLL).
C does not follow any of these categories. C falls in between two category. C is a neither High level nor Low
level. C is a Middle Level Language (MLD).

Various Stages in Evolution of C


Year Language Developed by Remarks

1960 ALGOL International Too General, too


(ALGOrithmic Language) Committee abstract

1963 CPL Cambridge University Hard to learn, difficult


(Combined/Cambridge to implement
Programming Language)

1967 BCPL Martin Richards at Too specific, deals


(Basic CPL) Cambridge University with specific problem
1970 B Ken Thompson at AT Too specific, deals
(From BCPL-the first letter ) & T’s Bell Labs with specific problem

1972 C Dennis Ritchie at AT supported generality


(From BCPL-the second & T’s Bell Labs
letter )

2.4.4 Structure of C Program

Documentation Section

Linker/Preprocessor Section

Definition Section

Global Declaration Section

main()
{
Variable declaration section;
Function declaration section
Executable statements;
}

Sub Program Section


Function Definition 1
{
Body of the Function;
}
……..
……..
Function Definition n
{
Body of the Function;
}

Documentation Section
The documentation section consists of a set of comment lines specifying the name of the program, description
about a statement and other details, which the programmer would like to use later.
Example :
/* This program developed by Mr dennis ritchie
on 1/2/1988 */
//Sum of 2 number
Note: // it indicates single line comment and /* */ indicates multi-line comment
Link/Preprocessor Statements
The preprocessor statement begins with # symbol and is also called as the preprocessor directive.
These statements instruct the compiler to include C preprocessors such as header files and symbolic constants
before compiling the C program.
Some of the preprocessor statements are listed below.
#include<stdio.h>
#include<conio.h> Header files
#include<math.h>
#include<stdlib.h>
Definition Section
It is used to define or set values to variables and define symbolic constants
Example: #define PI 3.14
Symbolic Constants
#define TRUE 1
#define TN TamilNadu
Global Declaration Section
In C There are two types of declarations
1. Local variable declaration
2. Global variable Declaration
Global variables are declared outside the main function. Local variables are declared inside the main function.
These global variables can be accessed by all the user defined functions including main ( ) function, whereas a
local variable can be accessed by only the main() function.

main() function
Every C program must have one main function section. This section contains two parts, declaration and
executable part.
Note: The C program execution starts with main ( ) function.
General form:
main()
{
local variables declaration
computational part
logical part
}

Variable Declaration
It declares all the variables that will be used in the executable part.
All statements in the declaration part should end with the semicolon.
Syntax:
Data-Type Variable-Name;
Example:
int a,x;
float b,c;
char name;
Executable part
It consists if single statement or block of statements that contain instructions to perform certain task.
Example:
a=x*x;
Subprogram Section
The Subprogram Section contains all the user defined functions that are called in the main function.

2.4.5 An Example Program


Program (area.c)

//Program for calculating the area of circle


#include<stdio.h>
#define pi 3.14
void main()
{
int area;
int radius=5;
area=pi*radius*radius;
printf(“%d”,radius);
}
Output:
78.5

Explanation
//Program for calculating the area of a circle Comment

#include<stdio.h> Header Files

Preprocessor Directive
#define pi 3.14

void main() main function


{ Declaration Part
int area;
int radius=5;
Initialization Part
area=pi*radius*radius;
printf(“%d”,radius); Executable Part
}
2.4.6 Guidelines for Developing a Good C Program
Characteristics of a good program.
Clarity: The program should be understood easily even without the help of the programmer who has written the
code. The program should unambiguously (clearly) depicts the logic of the program.
Integrity: It refers to the accuracy of the program. Integrity ensures that program does the specific task
correctly.
Efficiency: Efficiency of a program depends on how fast the program executes and how less memory space it
needs for executing the program.
Modularity: Modularity of program means dividing the program into small components according to its
functionality.
If the program is divided into independent modules error detection and correction would be easy.
Important points:
1. The program should be easily understood by any one.
2. It should be error free.
3. Use proper indentation(it is the ordering of the curly braces)
4. Avoid heavily nested loops.
5. It should work correctly for all possible sets of input.
6. It should execute as fast as possible.
7. It should take as less memory as possible
Comment
 Comments are good way to better understanding of the program statements.
 Comments, which are not executable statement.
 Comments are used to document the program.
 Comments can be single line or multi line.

Single Line Comment


Comments are non-executable code used to provide documentation to programmer. Single Line Comment is
used to comment out just Single Line in the Code.
1. Single Line Comment Can be Placed Anywhere
2. Single Line Comment Starts with ‘//’
3. Any Symbols written after ‘//’ are ignored by Compiler in that particular line
Example :
#include<stdio.h>
void main()
{
printf("Hello"); //Single Line Comment
printf("By");
}
#include<stdio.h>
void main()
{
printf("Hello"); // ********** Until Line Ends *****
printf("By");
}

Multi Line Comment


 Multi Line Comment Can be placed anywhere.
 Multi Line Comment Starts with ‘/*’.
 Multi Line Comment Ends with ‘*/’.
 Any Symbols written between ‘/*’ and ‘*/’ are ignored by Compiler.
 It can be span over multiple Lines
Example1 :
#include<stdio.h>
void main()
{
printf("Hello");
/* Multi
Line
Comment
*/
printf("By");
}
Example2:
#include<stdio.h>
void main()
{
printf("Hello");
/*-------------------------------------------------
------------------Ignored by compiler-------
--------------------------------------------------
*/
printf("By");
}

Multi-line Comment Single-line Comments


Starts with /* and ends with */ Starts with //
All Words and Statements written between /* and Statements after the symbol // up to the end of
*/ are ignored line are ignored
Comment Ends whenever ENTER is Pressed and
Comment ends when */ Occurs
New Line Starts
e.g. /* This is Multiline Comment */ e.g. // Single line Comment

The Semicolon
The semicolon serves as the statement terminator. Each executable statement should have a “;” to inform the
compiler that the statement has ended. Thus, in ‘C’ the semicolon terminates each statement.
Note: if you forget to place a semicolon before a statement, then “statement missing” error will be generated by
the compiler

2.5 Compilation and linking process


Before getting to know what a compilation is and linking process, we should know some basics about translator,
linker and loader.

2.5.1 Need for Translator


 A translator is needed when you want to convert a program written in one programming language into
another programming language.
 It is just like converting a dialogue written in English into Tamil without affecting the meaning.
 Translator translates program written in one programming language into (equivalent) program written in
another programming language without changing the logic of the program.
There are three types of translator.
 Compiler
 Interpreter
 Assembler

Compiler: If the translator translates a high level language into a lower level language it is called a Compiler.
Interpreter: If the translator translates each statement in a high level language into an intermediate code
immediately before executing the next statement in a line by line manner, it is called an Interpreter.
When an error is encounter, the execution will not go to the next instruction.
Decompiler: If the translator translates target/machine code to source language it is called a Decompiler.
Assembler: If the translator translates assembly language to machine code it is called an Assembler.
Disassembler: If the translator translates machine code into assembly language it is called a Disassembler.

Difference Between Compiler and Interpreter


No Compiler Interpreter
1 Compiler Takes Entire program as input Interpreter Takes Single instruction as input.
2 Intermediate Object Code is Generated No Intermediate Object Code is Generated
3 Conditional Control Statements Executes Conditional Control Statements Executes slower
faster
4 Memory Requirement is More (Since Memory Requirement is Less
Object Code is Generated)
5 Program need not be compiled every time Every time higher level program is converted into
lower level program
6 Errors are displayed after entire program is Errors are displayed for every instruction
checked interpreted
7 Example : C Compiler Example : BASIC, Perl, Python, MATLAB and
Ruby

Need for a linker : It is a Tool that merges the object files produced by the compilation process and creates an
executable file
Need for a loader: Loader is a Part of the Operating System that brings an executable file residing on disk into
memory and allows the file to be executed.

2.5.2 Steps Involved in Running a C Program


1. Write a program in a C editor.
2. Compile the program to check if there is any error, if so correct the error.
3. Link the program with system library.
4. Run the program

Create/Modify Source Code

Source code (developed by the programmer)

#include<stdio.h>
void main()
Source Code
{
printf(“Hai”);
}

Compile Source Code

i.e., AltIf+compilation
F9 errors

Object File

Run Object Code

i.e., Ctrl + F9

Executable
Code
Entering, Translating, and Running a High-Level Language Program

Flow of Execution
Source Code Object Code Execute Code
Compile Run
Program.C Program.obj Program.exe

Save

Program.bak

Backup Code
Step1:
Whenever you create a program, it is called as source code (Program.c). When you save the program, the
compiler automatically creates a file with “bak” extension (Program.bak).
Step2:
After compiling the program, an object file is created (Program.obj).
Step3:
After executing the code an executable file is generated.(Program.exe).

2.6 Constants, Variables and Data Types


2.6.1 Who Can Learn C
 C is the basic requisite for learning any programming language.
 C does not require any prior knowledge.
 Anyone who knows English alphabets can start to learn C.
 Anyone who has good logical thinking can write great programs in C.

2.6.2 C Character Set

 Character set is the collection of all possible characters used in c.


 From character set data types, constants variables and keywords are derived.
 From keywords, instructions can be formed.
 A set of instructions is called as Program.
Character Set:
 A Set of Alphabets (A-Z, a-z), Digits (0-9), White spaces and Special Symbols are called Character Set.
 Each character is represented by a unique Value.
 Each of these characters are represented by a code suggested by American Standard Code for
Information Interchange(ASCII)
character set

Alphabets Digits White spaces Special Symbols

Alphabets: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
abcdefghijklmnopqrstuvwxyz
Digits: 0123456789

Symbols:
~ Tilde “ Quotation mark ` Apostrophe
! Exclamation mark ; Semicolon - Minus sign
# Number sign < Opening angle bracket = Equal to sign
$ Dollar sign > Closing angle bracket { Left brace
% Percent sign ? Question mark } Right brace
^ Caret , Comma [ Left bracket
& Ampersand . Period ] Right bracket
* Asterisk / Slash : Colon
( Left parenthesis _ Underscore + Plus sign
) Right parenthesis | Vertical bar \ Backslash

Delimiters:
Symbol Delimiters Use
: colon used at the end of a label
; Semicolon Used at the end of the statement
() Parenthesis Used in expressions and function
[] Square bracket Used for array declaration
{} Curly braces Used to represent block of statements
# Hash Used in pre processor directives
, Comma Used to separate values
2.6.3 C Tokens
 Smallest individual units in C program are known as token.
 Example: Data Types, Constants, variables and Keywords
 C token is any individual word present in the c-language.
 There are classified into six types
Keywords
 Keywords are special word reserved by the compiler.
 Each keyword has a specific purpose.
 In c language there are 32 keywords

auto Else register union

break Enum return unsigned

case Extern short void

Char Float signed volatile

const For size of while

continue Goto static typedef

default If struct long

do Int switch double

Constants:
 The value which will not be changed during the execution of the program are called constants
 Example: 5,7.25,’a’ etc
Note: usually a constant will be place on the right hand side of the assignment operator (=).
variables:
 The values which may be changed during the execution of the program are called variables.
 Example: marks, height, sum etc
Note: usually a constant will be place on the left hand side of the assignment operator (=).
marks = 70
variable Constant

Assignment
operator
Strings:
 Group of characters enclosed within double quotes " "
 Example:”I am a string”
Operators:
 Operators are mathematical symbols which are used in evaluation of expression.
 Example: +,-*,/ etc
Special Symbols:
 Each special symbol has its own meaning
 Comma (,) – It is used to separate values.
 Semi colon (;) –It is used to notify the end of a statement.
 Ampersand (&) –It is used to print the address of a variable.
2.6.4 Constants
Why Constants?
Constants can be very useful in C programming whenever you have a value that will be repeated in a program.
You can declare a constant and use it in your program as many times you want, and if you want to change the
value of the constant you need not change every occurrence of the constant but only its declaration.
What is Constants?
Constants are values that never change. (The constants value is locked for the entire duration of the program).
Pi for instance is a good example to declare as a constant.
Example pi =3.14;

Types of Constants
Constant can be classified into the following.
1. Primary Constants
2. Secondary Constants
Primary constants are further classified into Integer constant, real constant, single character constant, string
constant, string constant Backlash character constants.

Constants

Primary Constants Secondary Constants


Integer Constants:
An integer constant is an integer quantity which contains a sequence of digits.
Rules for Constructing Integer Constants
- An integer constant must have at least one digit.
- It must not have a decimal point.
- It can be either positive or negative.
- If no sign precedes an integer constant it is assumed to be positive
- No commas or blanks are allowed within an integer constant.
- The allowable range for integer constants is -32768 to 32767.
Example of valid integer constants: - 976 8987 5 -25 etc.
Example of invalid integer constants:- 78.43 7-8 89,76 etc

Floating Point Constants


They are also known as real constants.
A real constant contains a decimal point or an exponent.
Rules for Constructing Floating Point Constants
- A real constant must have at least one digit.
- It must have a decimal point.
- It could be either positive or negative.
- Default sign is positive.
- No commas or blanks are allowed within a real constant.
Examples:- 254.175, -16.47 -0.5e-7 +4.1e8

Character Constant
A character constant is a character which is enclosed in single quotes.
The size of a character constant is 1 byte and can contain only 1 character.
A character can be an lowercase alphabet like a, b etc or an uppercase alphabet like A,C etc or a special
character like &,^, $, #,@ etc or a single digit from 0 to 9.
It can also be an escape sequence character like space ‘ ‘ , a null character ‘\o’ or a new line character ‘\n’ etc.
Rules for Constructing character Point Constants
- A character constant should be an alphabet, a single digit or a single special symbol enclosed within
inverted commas.
- Both the inverted commas should point to the left. For example, ’R’ is a valid character constant
whereas ‘R’ is not.
- The maximum length of a character constant can be 1 character. 1 byte of memory is allocated
Example: ‘A’ ‘a’ ‘b’ ’8′ ‘#’ etc.

String Constants
A string constant is a collection of characters enclosed in double quotations “”. It may contain alphabets, digits,
special characters and blank space.
Rules for Constructing String Constants
- A character string, a string constant consists of a sequence of characters enclosed in double quotes.
- A string constant may consist of any combination of digits, letters, escaped sequences and spaces.

Note: A character constant ’A’ and the corresponding single character string constant "A" are not equivalent.
Example: “Monday” “C programming” “123”
Difference between character constant and string constant
Character Constant String Constant
A character constant is enclosed within single A sequence of characters enclosed in double
inverted commas. quotes
The maximum length of a character constant is one A string constant can be of any length.
character.
A single character string constant has an equivalent A single character string constant does not
integer value (ASCII value). have an equivalent integer value.
Example: Equivalent value of lowercase letter ‘d’
is 100
A single character requires one byte. A single string constant requires two bytes.
One byte for the character constant and another
byte for “null” (\0) character.
Example: Example:
char a = ‘d’; char a[] = ‘d’;
d d \0
1010 1010 1011

Every character constant does not end up with a Every string constant ends up with a NULL
NULL character. character (‘\0’). It is automatically assigned by
the compiler

void main()
{
int a =10; // integer constant
float b = 7.25; // floating point constant
char c =’a’; // character constant
char d[4] = “hai”; // string constant
char d[2] = “a”; // single string constant
}

Backslash Character Constants


C language supports some special backslash character constants that are used in output functions.
Each backslash sequence consists of a
1. backslash character and
2. character after it.
These combinations are also known as escape sequences.
Some important points about backslash character constants:
 Though it consists of two characters, it is represented as single character.
 Each escape sequence has unique ASCII value.
 They are non-printable characters.
 Escape Sequences are preprocessed by Preprocessor.

Purpose of backslash character:


 It is used to format the output.

 It is used to print characters like “,’,\,


A few backslash characters and its meaning are listed below

Constant Meaning Constant Meaning


\a audible alert (bell) \v vertical tab
\b back space \’ single quote
\f form feed \” double quote
\n new line \\ backslash
\r carriage return \0 null
\t horizontal tab

Some of the backslash character are explained with a program below:

1. ‘\t’ Character

 It is Horizontal Tab
 The cursor is moved forward 8 spaces

#include<stdio.h>

int main()
{
printf("Hello\t");
return(0);
}

Cursor Position After Execution of printf :

Hello _

2. ‘\n’ Character

 It is New Line Character


 The cursor is moved to new Line

#include<stdio.h>

int main()
{
printf("Hello\n");
return(0);
}

Cursor Position After printf :

Hello
_

3. ‘\b’ Character

 It is Backslash Character
 It moves cursor one position back

#include<stdio.h>

int main()
{
printf("Hello\b");
return(0);
}

Cursor Position after printf:

Hello

Note : the cursor is on ‘o’ character in the Word “Hello”

4. ‘\r’ Character

 It is Carriage Return Character


 It moves the cursor to the First Position in the Line

#include<stdio.h>

int main()
{
printf("Hello\r");
return(0);
}

Cursor Position after printf:

Hello
Note : the cursor is on ‘h’ character in the Word “Hello”

5. ‘\a’ Character

 It is audible Return Character


 Beeps Sound

printf("Hello\a");

Cursor Position after printf:

Hello_

Note: After printing hello, the System will give a Beep sound.

.
2.6.5 Variables
Introduction
The variables are nothing but the name given to a value.
Example: marks=72
In the above example 72 is a value and we give a name called “marks” to that value. Here the “marks” is a
variable.
We usually remember a person by their name rather than by their mobile number. So we can store their mobile
number(value) by their name(which we can easily remember)
Example: Raja=987654321
In the above example Raja(name) is the variable and 987654321(mobile number) is the value
Note: similar to the constants, variables are also classified into different types but the value of the variable
can be changed during the execution of the program.

2.6.5.1 Rules for Naming the Variables


Variable can be a collection of alphabets, digits and underscore (_), but there are some rules in defining the
variable.
1. Any variables should start with a character or underscore , it should not start with a digit
2. No special symbols should be used, except the underscore symbol.
3. White spaces should not be used.

Example 1: 3ab
It is Contrary to rule 1 as it starts with a number

Example 2: $marks
It is Contrary to rule 2 as it contains the special symbol $

Example 3:my marks


Contrary to rule 3 as there is a white space between my and marks

Some valid variable declarations


ab3 A a3b
mymarks my_marks MyMarks
Abc Abc
Note: Variables are case-sensitive. Example abc and Abc are two different variables

2.6.5.2 Declaration Vs Initialization


Declaration
The purpose of declaring a variable is to tell the compiler to reserve a memory space for the variable according
to its data type.
Syntax:
<datatype > <variableName>
Or
<storage class><datatype > <variableName>
Example :
int a;
float f;
char c;
auto int b;

Storage class

Here memory space is reserved for the variable value b under auto storage class.
Initialization
The purpose of initialization is to assign a value to the variable.
E.g.: a=5;
Here the value 5 is assigned to the variable a.
Note: If the variable is not initialized after declaration, it will contain some random value called the
garbage value.

2.6.5.3 Life of a Variable


The life of the variable is nothing but the time until which the variable exists.

Note: No variable can exist after the program is terminated

4.3.5.4 Local VS Global


Local Variable Global Variable
A variable is said to be a local variable if it can A variable is said to be a global variable if it can
be used only within a particular block of a be used from anywhere within the program.
program where it is declared.
A local variable will be destroyed once the A global variable will be destroyed only when
program execution comes out of the block of the the program is terminated.
program.
The scope of the variable is only within the The scope of the variable is throughout the
particular block of the program. program.
It is usually declared inside the main function. It is usually declared outside the function.
It is created in the stack area of the memory. It is created in the heap area of the memory.
.
2.6.5.5 Storage Class- auto ,register ,static and extern
In C there are four types of storage class. They are:
1. auto
2. register
3. static
4. extern
Storage class is modifier or qualifier of data types which decides:
1. In which area of memory a particular variable will be stored?
2. What is life of variable?
3. What is scope of variable?
4. What will be the initial value of the variable, if initial value is not explicitly assigned?

2.6.6 Data Types


Data: Any unprocessed information is called Data.
Example: 20 is a data
Machine can understand only data and not the information. so we can give input to the computer as only data.
Information: Any processed data is called information.
Example: 20 rupees is a information
Since human can understand the information ,the machine process the data and give the information to the
humans
Any data will be stored in a computer memory only with the help of variables.
Data can be classified as integer, real numbers, characters etc and they are called as data types.
C supports wide range of data types and the programmers can choose the data types according to their
requirements.
Data types can be classified as follows

Datatype

User
primary Derived
defined

int float char array structure union pointer enum typedef


Primary Data can be broadly classified as follows

INTEGER CHARACTER FLOAT


DATA TYPE TYPE DATA TYPE

SIGNED UNSIGNED LONG


SIGNED UNSIGNED CHAR FLOAT DOUBLE
CHAR CHAR DOUBLE

UNSIGNED UNSIGNED UNSIGNED


INT SHORT INT LONG INT
INT SHORT INT LONG INT

TYPE SIZ Range Example Format


E specifier
(Bits
)
char or signed char 8 -128 to 127 char ch=’b’ %c

unsigned char 8 0 to 255 unsigned char ch =’b’ %c


int or signed int 16 -32768 to 32767 int a=2 %d or
%i
unsigned int 16 0 to 65535 unsigned int a=2 %u
short int or signed short 8 -128 to 127 short int a=2 %d or
int %i
unsigned short int 8 0 to 255 unsigned short int %u
a=2
long int or signed long int 32 -2147483648 to long int a=2 %ld
2147483647
unsigned long int 32 0 to 4294967295 unsigned long int %lu
a=2
float 32 3.4 e-38 to 3.4 e+38 float a=3.14 %f or
%g
double 64 1.7e-308 to 1.7e+308 Double a =3.14 %lf
long double 80 3.4 e-4932 to 3.4 Long double a = 3.14 %lf
e+4932
Example Program
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int x = 32760 ; int x = 32769 ;
printf(“x = ”,x); printf(“x = ”,x);
} }
Output: x = 32760 Output: x = -32767
Explanation: the value which we tried to print
is out of the range of the integer (-32768 to
+32767) and so some garbage value (random
value) is printed.

Note: so one should know the range of the data type to avoid the above problem

Format specifier:
 Format specifiers are the operators used in printf() function to print the value which is referred by a
variable.
 We can retrieve the data stored in the variables and can print them on to the console screen by using
these format specifiers in a printf() function.
 It tells the compiler whether the integer, character or floating point value should be printed
 Format specifiers start with a percentage (%) symbol and follow a special character to identify the type
of the data.
 Example %d, %f etc
Type Definition
In C language a user can give a new name to an existing data type. The user defined data type identifier can later
be used to declare variables.
Syntax:
typedef type identifier
Here ‘typedef’ is the keyword, ‘type’ represents existing data type and ‘identifier’ refers to the new name given
to the data type.
Example:
typedef int salary;
Now we can declare a variable by using
salary abc;
instead of using
int abc;
Program
//Typedef Example
#include <stdio.h>
#include <stdlib.h>
void main()
{
typedef int salary;
salary a=100;
printf("My Salaray = %d",a);
}
Output :
My Salary = 100
Enumerated Data Type
The enumerated data type also called as enum is user defined data type
Enumerated data types are particularly useful while creating a new data types that can take only a restricted
range of values.
For Example, the direction can take only four values such as north, south, east and west.
If set the value of direction to be 123, then it would be meaningless so we use enumerated data types to restrict
such meaningless assignment.
Syntax:
enum identifier {value1,value2,value3…..valueN}
Example :
enum directions { NORTH,SOUTH,EAST,WEST };
2.6.7 Type Conversion
A type conversion is the process of converting one data type into another data type. This is sometimes also
called as type casting.
For example if you want to store a float value into an integer then you can type cast float to int.
Casting
Conversion between data types can be done in two ways by casting:
 Implicit casting
 Explicit casting
Implicit casting
Implicit casting doesn't require a casting operator. This casting is normally used when converting data from
smaller integral types to larger integral types.
int x = 123;
float y = x;
In the above statement, the conversion of data from int to float is done implicitly, in other words programmer
doesn’t need to specify any casting operators.
It is also called as automatic Type casting.
Explicit casting
This casting is normally used when converting a larger data type to smaller data types. Explicit casting requires a
casting operator.
Syntax
<variable>=(datatype)<expression>
Example
float y = 123;
int x = (int)y;
In the above Example, we have to specify the casting operator (int) explicitly when converting from float to int,
because the size of the float is 4 bytes and size of the integer is 2 bytes and we cannot fit 4 byte value into a 2
byte value.
2.6.8 Keywords

2.7 Expression using Operators


Operators are nothing but any mathematical symbol used in the evaluation of an expression.
Consider the following expressions
Expression 1
b*a;
Here a, b are called operands and * is called operators
Expression 2
c = b*a;
Here a, b, c are called operands and =,* are called operators

2.7.1 Need for Operators


 An operator indicates an operation to be performed on an operand to yield a value.
 Any expression can be evaluated only with the help of the operator.
 Without the operators there are no expressions.
2.7.2 Types of Operators
The operators are classified into different types based on their operations on the operands.
Some operator requires at least two operands and some operator may work with a single operand itself.
2.7.2.1 Arithmetic Operators
The arithmetic operator performs the basic arithmetic functions. The arithmetic operators and its meaning are
listed below
Consider that a = 14 and b=7

Operator Name Description Example Result


+ addition Adds two operands a+b 21
- Subtraction Subtracts second operand from the a-b 7
first
* Multiplication Multiply both operands a*b 98
/ Division Divide numerator by denominator a/b 2
% Modulo Yields the remainder after an a%b 0
division
++ Increment Increases the integer value by one a++ 15
-- Decrement decreases integer value by one b-- 6
.
2.7.2.2 Relational Operators
The relational operators are mainly used for comparison.
The relational operators take only two values i.e. 0 and 1.
When the condition is true the value assigned to the expression will be 1 and if the condition is false then the
value assigned will be 0
Consider that a=10 and b=10.
Operator Name Description Example Result
Equal to Checks if the value of two operands
+ a==b 1
is equal.
Not equal to Checks if the value of two operands
- a !=b 0
are not equal.
Greater Checks if the value of left operand is
* than greater than the value of right a>b 0
operand
Less than Checks if the value of left operand is
/ a<b 0
less than the value of right operand
Greater than Checks if the value of left operand is
% or equal to greater than or equal to the value of a>=b 1
right operand
Less than or Checks if the value of left operand is
++ equal to less than or equal to the value of right a<=b 1
operand,
.
2.7.2.3 Logical Operators
The logical operator works exactly like the logical gates.
Consider a=0 and b=1;
Similar to the relational operator the output of a logical operator will be either 1 or 0
Operator Name Description Example Result
Logical If both the operands are non zero then
&& a &&b 0
AND condition becomes true.
If any one of the operand is non zero the
|| Logical OR a || b 1
condition becomes true
It works with only a single operand.
!a 1
Logical It reverses the value of the operand i.e if
!
NOT the value of the operand is 0, the output
!b 0
will be 1 and vice versa
.
2.7.2.5 Increment and Decrement Operators
Increment operator
It is used to increase the value of operand by 1;
It can be written as
a++ or a=a+1;
If the value of a is 5 then after increment the value of a will be 6.

Pre Increment Vs Post Increment

Pre increment operator first increments the value and then assigns the value to the variable.
Example
c=++a;
If the value of a=5 ,then the value of c will be 6

Post increment operator first assigns the value to the variable and then increments the value.
Example
C=a++;
If the value of a=5 ,then the value of c will remain 5 as it will be incremented only after assigning
Decrement operator
It is used to decrease the value of operand by 1;
It can be written as
a-- or a=a-1;
If the value of a is 5 then after decrement the value of a will be 4.

Pre Decrement Vs Post Decrement


Pre decrement operator first decrements the value and then assigns the value to the variable.
Example
C = --a;
If the value of a=5, then the value of c will be 4.
Post decrement
Post decrement operator first assigns the value to the variable and then decrements the value.
Example
c=a--;
If the value of a=5, then the value of c will remain 5 as it will be decremented only after assigning the value to
the variable.
Example Program
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int x , y; int x , y;
x=5; x=5;
y=10; y=10;
Output:x=%d\n, x++");
printf(" Output: --x");
printf(" x=%d\n,
X = 5 y=%d\n, ++y");
printf(" X = 4 y--");
printf(" y=%d\n,
} Y = 11 } Y = 10

2.7.2.6 Conditional or Ternary operators


 This operator consists of two symbols: The question mark (?) and the colon (:)
 This is the only operator that uses three operands
 It is also called as the ternary operators, because ternary means three.
 This is the only operator that uses three operands
Syntax:
(Test expression)? Expression1: Expression2

(operand 1) (operand 2) (operand 3)

The test expression contains the expression to be evaluated and if the value of the test expression is true then
Expression1 is executed and if the value of the test expression is false then the value of the Expression2 is
executed

A classical example of the conditional operators

(value >= 0)?printf(“positive”): printf(“negative”);


Example program
#include<stdio.h>
void main()
{
int value =10;
(value >= 0)?printf(“positive”): printf(“negative”);
}

Output:
positive

If the value is greater than zero the compiler prints as positive, else it prints as negative

2.7.2.7 Bitwise Operators


 In bitwise operators, the value operand will be treated as binary number and the operations will be
performed on Each bit.
 The bitwise operators are &, | , ^
 The bitwise operators works based on the following truth table
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

Consider the value of a = 60 b =13


Binary value of a is 00111100
Binary value of b is 00001101
a & b is 0 0 0 0 1 1 0 0 => decimal value of 12
a | b is 0 0 1 1 1 1 0 1 => decimal value of 61
a ^ b is 0 0 1 1 0 0 0 1 => decimal value of 49
~a is 1 1 0 0 0 0 1 1 => decimal value of -60
a<<2 1 1 1 1 0 0 0 0 => decimal value of 240
a>>2 0 0 0 0 1 1 1 1 => decimal value of 15

Operato Name Description Example Result


r
Bitwise If both the operands are non zero then
& a &b 12
AND condition becomes true.
If any one of the operand is non zero
| Bitwise OR a|b 61
the condition becomes true
Bitwise If both the operands are same then
^ Exclusive output is zero ,else it is one a^b 49
OR
It inverts every bit
Bitwise
~ a~b -60
negation

The binary value of left operands is


Left shift
<< moved left by the number of bits a<<b 240
operator
specified by the right operand.
The binary value of left operands is
Right
>> moved right by the number of bits a>>b 15
operator
specified by the right operand
.
2.7.2.4 Assignment Operators
Assignment operator ( =) has two operands, one on the left hand side of the operator and other on the right hand
side of the operator.
Syntax
operand1 = operand2;

(left hand (operator) (right hand


Side side
operand) operand)
Assignment operator assigns the value of the RHS operand to the LHS operand
Example
a=20;
Here the value of 20 is assigned to b.
Consider that the value of X=10 and value of Y= 3
Operato Description
Name Example Result
r
Simple Assigns values from right side X=3
= X=Y
assignment operands to left side operand Y=3
It adds right operand to the left
ADD and X=13
+= operand and assign the result to left X+=Y
ASSIGN Y=3
operand
SUBTRACT It subtracts right operand from the left
X=-7
-= and operand and assign the result to left X-=Y
Y=3
ASSIGN operand
MULTIPLY It multiplies right operand with the
X=21
*= and left operand and assign the result to X*=Y
Y=3
ASSIGN left operand
It divides left operand with the right
DIVIDE and X=3
/= operand and assign the result to left X/=Y
ASSIGN Y=3
operand
MODULUS It takes modulus using two operands
X=3
%= and and assign the result to left operand X%=Y
Y=3
ASSIGN
.
2.7.2.8 More Operators
Comma operator ( , )
Comma operator is used to separate the expressions.
The general syntax of the comma operator is
Expression1, Expression2, …, ExpressionN.
The expressions separated by the comma operator are evaluated from left to right i.e the Expression1 is first
executed followed by Expression2 and finally the expressionN is evaluated.

Example
int i , j;
i=(j=10,j+20);
Here the expression j=10 is first evaluated (the value of j is 10) and then the expression j+20 is then evaluated
(now the value of j is 30) and finally the value of j is assigned to i.

sizeof operator
The sizeof operator returns the size of its operand in bytes.
The general syntax of the sizeof operator is
sizeof(operand)
Example
int i;
char j;
We already know that the length of the integer is 2 bytes and length of the character is 1 byte.
so,
sizeof(i) returns the value of 2 and
sizeof(j) returns the value of 1

2.7.3 Properties of Operator


The properties of an operator are operator precedence or priority and they play an important role in evaluating an
expression unambiguously
For example
The compiler will not know whether the expression 2 * x - 3 * y should be evaluated as (2x)-(3y) or 2(x-3y).
The solution to the above problem is given by operator precedence and associativity

2.7.3.1 Operator Precedence or Priority


The operator precedence or priority determines which operator should be evaluated first
Priority Operators
1st */%
2nd +-
3rd =

Consider the example


Step1 : a=6*5+4
here since * has the highest priority and it is evaluated(6*5=30)
Step 2 : a=30+4
here + has higher priority than = and it is evaluated(30+4=34)
Step 3 : a=34
Finally the assignment operator = is evaluated and the value of 34 is assigned to a
2.7.3.2 Operator Associativity
When an expression contains more than one operator having equal priority, then the compiler will not know
which of the two equally prioritized operators should be evaluated first and here the operator associativity comes
into play.
The operator associativity will be of two types
1. left to right
2. right to left
Left to Right associativity means that the left operand must be unambiguous.
Right to Left associativity the right operand must be unambiguous.
Note: Unambiguous means the operand must not be involved in evaluation of any other sub-expression.
This will be better understood with the help of an example
Consider the expression
x=4/2*6
Here both the * and / have equal priority and now operator associativity determines which operator will be
evaluated first.
Both the * and / has left to right associativity and so the operator for which the left operand is unambiguous will
be evaluated first.

Remark
Operator Left Right

2*6 Right operand is involved in sub-expression and left


/ 4 (sub- operand is not involved in sub-expression.
expression) Here the left operand is unambiguous
4/2 Left operand is involved in sub-expression and right
* (sub- 6 operand is not involved in sub-expression
expression) Here the right operand is unambiguous

So only for the / operator the left operand is unambiguous and so it will be evaluated first.
Now x = 2* 6.
Here * has higher priority than = and it is evaluated(2*6 = 12)
Now x = 12
Finally the assignment operator = is evaluated and the value of 12 is assigned to the variable x

2.8 Managing Input and Output Operators


Introduction
Classification of I/O
• There are numerous library functions available for I/O. These can be classified into two broad categories
(a) Console I/O functions - Functions to receive input from keyboard and write output to Visual Display
Unit (monitor screen).
(b) File I/O functions - Functions to perform I/O operations on a secondary storage floppy disk or hard
disk.
Console I/O Function
• The screen and keyboard together are called a console.
• Console I/O functions can be further classified into two categories.
1. formatted console I/O functions
2. Unformatted console I/O functions.
The basic difference between them is that the formatted functions allow the input read from the keyboard or the
output displayed on the VDU to be formatted as per our requirements whereas unformatted console I/O
functions cannot be formatted.

2.8.1 Need for I/O Operators

Console I/O in general means communications with the computer's keyboard (input) and display (output).
The program uses console I/O
 To simply read its "standard input (stdin)" - which might be the keyboard, a file dump, or the output of
some other program.
 To print its "standard output (stdout)" -- which might be the monitor or printer or another program or a
file.
I/O can be classified into two broad categories
(a) Console I/O functions - Functions to receive input from keyboard and write output to display screen.
(b) File I/O functions - Functions to perform I/O operations on a disk or file.
2.8.2 Input and Output Functions
There are numerous I/O functions and are listed below
2.8.3 Formatted I/O Functions
 In the formatted I/O functions, the input data or the output function are formatted as per requirement.
 It gives a clear and legible view of the output.
 With the formatted I/O functions one can decide how the output should appear on the screen.
 The formatted I/O functions have a format string (%d, %s) in the function.
2.8.3.1 printf()
The formatted function used to display the output is printf().
If you are going to print any message ,you can simply include the message within the double quotes in the
printf() function
Example
void main()
{
printf(“my message”);
}
If a variable has to be printed, then the data type of the variable should also be specified using the format
specifier.
Syntax
printf(“format specifier”, variableName);
Example
void main()
{
printf(“%d”,a);
}
Generally, the variable will be printed only in the format specified by the format specifier.
Consider the example program
void main()
{
char variable=’a’;
printf(“%d”,a);
}
Output:
97

Now we may not able to predict the output as the variable a is declared as character data type and the
format specifier is given as %d (integer data type)
As it is mentioned earlier the variable a will be converted into integer data type (the corresponding ASCII value
of a is 97) and the output will be displayed as 97.

Return Value of printf()


 printf() will return an integer value
 On success, the printf() functions return the number of bytes that has been displayed
 On error, these functions return EOF
Example :
void main()
{
int n;
n = printf(“Welcome”);
}
Output: n = 7

Here the string welcome consists of seven characters (7 bytes) and so the output will be printed as 7.

What is format specifier


 Format specifiers will have the following form:
% [flags] [width] [.prec] type_char
 Each format specifier begins with the percent character (%) and ends with a conversion type character
(type_char). The flags, width and precision may or may not be present

Component What It Controls or Specifies


(Optional) It includes Flag character, Output justification, numeric signs, decimal
[flags]
points, trailing zeros, octal and hexadecimal prefixes.
(Optional) Width specifier specifies the Minimum number of characters to be
[width]
printed (if necessary the output is padded with blank spaces or zeros).
(Optional) Precision specifier specifies the Maximum number of characters to be
[.prec]
printed;
Type_char (Required) Conversion type character

What is Format String


 The format string controls how printf() function converts, formats and prints its arguments.

What is Conversion type character for data input


Data type Conversion type character
char or signed char c

unsigned char c
int or signed int d or i
unsigned int u
short int or signed short d or i
int
unsigned short int u
long int or signed long int ld
unsigned long int lu
float f or g
double lf
long double lf

Note : printf() based other formated I/O funcation are cprintf(), fprintf(), sprintf(), vfprintf(), vprintf(),
vsprintf()
2.8.3.2 scanf()
The formatted function used for getting the input from the user is scanf().
Syntax
scanf(“control string ”,&variable)
Example
scanf(“%d”,&a);
In the above example, an integer value is obtained from the user and it is stored in the variable a.
%d is the format specifier and it specifies the data type of the input variable.
The format specifier should be enclosed within the double quotes. Few basic format specifiers are listed below.
%d-the data is taken as integer
%c-the data is taken as character
%f-the data is taken as float
%s-the data is taken as string

Return value of scanf()


 scanf() will return an integer value
 On success, scanf() functions return the number of input fields successfully scanned, converted, and
stored.
 If Return value = 0, then it means no fields were stored.
 If Return value = EOF, then it means that scanf() attempts to read at end-of-file
Example:
void main()
{
int x;
x = scanf(“%d %d”,&a,&b);
printf(“%d”,x);
}
Output: 2
Here the output is 2 because scanf() functions successfully scans and stores two variables (a and b)
Note: Other scanf() related functions are cscanf(), fscanf(), sscanf(), vfscanf(), vscanf(), vsscanf().

2.8.3.3 Format Strings (Flags width and precision)


The flags width and precision gives more formatting to the output
Flag
The flag controls the 'characters' that are added to a string, like whether to append 0x to a hexadecimal number,
or whether to pad numbers with 0s.

The specific flag options are

The Pound Sign: #


Adding a # will cause
 a '0' to be prepended to an octal number (o is type conversion character for octal number), or
 a 0x to be prepended to a hexadecimal number (X is type conversion character for octal number).
For other type conversion character, adding a # will include a decimal point, even if the number has no fractional
part.
The Plus Sign Flag: +
The plus sign will include the sign specifier for the number:
For example
printf(“%+d”,10);
output:
+10
void main()
{
printf(“\n%X”,12);
printf(“\n%#X”12)
printf(“\n%o”,12);
printf(“\n%#o”,12);
printf(“\n%d”,12);
printf(“\n%#d”,12);
printf( "%+d\n", 10 );
}

Output:
C
0XC
14
014
12
12.0
+10

The Zero Flag: 0


Using 0 will force the number to be padded with 0s at the beginning. For example, if you set the width of a
number as 5,and if the number has less than 5 digits, then the remaining spaces of the number will be filled by
zeroes at the beginning.
For example
printf( "%05d\n", 10 );
output:
00010
Here the width is set as 5(%5d) and a zero flag has been included (%05d), but the number 10 has only two
digits, so the remaining three spaces will be filled by three zeros at the beginning.

The Minus Sign Flag: -


The minus sign will cause the output to be left-justified. For example, if you set the width of a number as 5,and
if the number has less than 5 digits, then the remaining spaces of the number will be filled by blank spaces at the
end.

printf( "|%-5d|%-5d|\n", 1, 2 );
output:
|1 |2 |
Here the width is set as 5(%5d) and a minus flag has been included (%-5d), but the number 10 has only two
digits, so the remaining three spaces will be filled by blank spaces after the number 10.
Example program
void main()
{
printf( "%05d\n", 1);
printf( "%04d\n", 1);
printf( "%03d\n", 1);
printf( "%02d\n", 1);
printf( "%01d\n", 1);
printf( "|%-5d|\n",2 );
printf( "|%-4d|\n",2 );
printf( "|%-3d|\n",2 );
printf( "|%-2d|\n",2 );
printf( "|%-1d|\n",2 );
}
Output:
00001
0001
001
01
1
|2 |
|2 |
|2 |
|2 |
|2|

Precision
The "precision" modifier is written as ".number".
It has slightly different meanings for the different conversion specifiers (like %d or %g).

For floating point numbers (%f)

It specifies the number of digits to be printed after the decimal point

If the number has less precision than specified, it will be filled with zeros.
For example:

printf( "%.3f", 1.2 );


output:
1.200
If the number has more precision than specified, it will be rounded off.
For example:
printf( "%.3f", 1.2348 );
output:
1.235

Example program:
void main()
{
printf( "%.6f\n", 1.2348 );
printf( "%.5f\n", 1.2348 );
printf( "%.4f\n", 1.2348 );
printf( "%.3f\n", 1.2348 );
printf( "%.2f\n", 1.2348 );
printf( "%.1f\n", 1.2348 );
printf( "%.0f\n", 1.2348 );
}

Output:
1.234800
1.23480
1.2348
1.235
1.23
1.2
1

For floating point numbers (%g)

It will control the number of significant figures displayed.


This will not consider only the numbers after the decimal point but the
whole number itself.
For example:
printf( "%.3g", 1.2348 );
output:
1.24
Comparing %f and %g

Example:
printf( "%.3f\n%.3g\n%.3f\n%.3g\n", 100.2, 100.2, 3.1415926, 3.1415926 );

100.200 // %.3f, putting 3 decimal places always


100 // %.3g, putting 3 significant figures
3.142 // %.3f, putting 3 decimal places again
3.14 // %.3g, putting 3 significant figures
void main()
{
printf( "%.6g\n", 125.7658 );
printf( "%.5g\n", 125.7658 );
printf( "%.4g\n", 125.7658 );
printf( "%.3g\n", 125.7658 );
}
output:
125.766
125.77
125.8
126

For integers(%d)
It controls the minimum number of digits that is to be printed.It fills the remaining spaces with zeros at the
beginning
Example 1
printf( "%.3d", 10 );
output:
010
For strings(%s)
It controls the maximum length of the string displayed
Example:
printf( "%.5s\n", "abcdefg" );
output:
"abcde"
Note: if you specify as '.0', then the number will have no output:
Example:
printf( "%.0s", “abcdefg” );
It has no output!
Example program:
void main()
{
printf( "%.6d\n", 125 );
printf( "%.5d\n", 125 );
printf( "%.4d\n", 125 );
printf( "%.3d\n", 125 );
printf( "%.2d\n", 125 );
printf( "%.1d\n", 125 );
printf( "%.8s\n", "abcdefg" );
printf( "%.7s\n", "abcdefg" );
printf( "%.6s\n", "abcdefg" );
printf( "%.5s\n", "abcdefg" );
printf( "%.4s\n", "abcdefg" );
printf( "%.3s\n", "abcdefg" );
printf( "%.2s\n", "abcdefg" );
printf( "%.1s\n", "abcdefg" );
printf( "%.0s\n", "abcdefg" );
}
Output:
000125
00125
0125
125
125
125
abcdefg
abcdefg
abcdef
abcde
abcd
abc
ab
a

Width
It has the same format as precision, but does not have a decimal point.
For integers(%d)
It controls the minimum number of digits that is to be printed.It fills the remaining spaces with blankspaces at
the beginning .
Example 1
printf( "|%3d", 10 );
output:
| 10
For strings(%s)
It controls the minimum length of the string displayed
Example:
printf( "|%8s\n", "abcd" );
output:
| abcd

Example program
void main()
{
printf( "|%6d\n", 125 );
printf( "|%5d\n", 125 );
printf( "|%4d\n", 125 );
printf( "|%3d\n", 125 );
printf( "|%2d\n", 125 );
printf( "|%1d\n", 125 );
printf( "|%8s\n", "abcd" );
printf( "|%7s\n", "abcd" );
printf( "|%6s\n", "abcd" );
printf( "|%5s\n", "abcd" );
printf( "|%4s\n", "abcd" );
printf( "|%3s\n", "abcd" );
printf( "|%2s\n", "abcd" );
printf( "|%1s\n", "abcd" );
printf( "|%0s\n", "abcd" );
}

Output:
| 125
| 125
| 125
|125
|125
|125
| abcd
| abcd
| abcd
| abcd
|abcd
|abcd
|abcd
|abcd
|abcd

The precision and width can be combined like,


<width>.<precision>
Example:
printf( "|%8.5f\n", 1.234 );
output:
| 1.23400
In the above example,
The width is 8 and so 7 blank spaces have been printed before the number 1.
The precision is 5 and so two zeros have printed after three decimal points

Output:
| 34.8
| 34.77
| 34.769
| 34.7689
| 34.76890
| 34.768900
| 34.7689000
|34.76890000

Note: the width considers the entire number including the digits after the decimal point,whereas the precision
considers only the digits after the decimal point.

2.8.4 Unformatted I/O Functions


 Unformatted Input/output is the most basic form of input/output.
 It does not do any formatting.
 Unformatted input/output transfers the internal binary representation of the data directly between
memory and the file.
2.8.4.1 Character Based I/O Functions
The character based I/O functions are based only on single character.
getchar()
 It is used to get (input) only one character at a time from keyboard.
 getchar() is a macro that gets a character from stdin.
 It is used to read the character from the user and stores it in the buffer until an Enter key is pressed.
 After pressing the Enter key, only the first character is processed and the remaining characters are
discarded.

Note: Macro is a piece of text that is expanded by the preprocessor. This is used to expand the text before
compiling.

Declaration
int getchar(void);
Example Declaration
char ch;
ch = getchar();
Return Value:
This function returns the character read from the keyboard.
Example Program:
void main()
{
char ch;
ch = getchar();
printf("Input Char Is :%c",ch);
}
Program Output:
A
Input Char Is:A
Working of getchar()
 During the program execution, a single character is read through the getchar () function.
 The given value is displayed on the screen and the compiler wait for another character to be
typed.
 If the enter key is pressed, the given character is printed through the printf function.

getch()
 getch() gets a character from console but does not print on the screen.
 This function reads a character and never waits for Enter key. It just gets processed after the first
key is being pressed.

Declaration:
int getch(void);
Example Declaration:
char ch;
ch = getch(); (or ) getch();
Return Value:
This function return the character read from the keyboard.
Example Program:
void main()
{
char ch;
ch = getch();
printf("Input Char Is :%c",ch);
}
Output:
Input Char Is : A
Working of getch()
 During the program execution, a single character is read through the getch().
 The given value is not displayed on the screen and the compiler does not wait for another character to be
typed.
 As soon as a key is pressed, it returns the character to the getch() function and the returned character is
printed through the printf function.
Note: usually a getch() is given at the last line of the main function ,to ensure that the program waits for
a key to pressed by the user before terminating.
It is done so that the user can view the output screen, otherwise the output screen will go off like a flash.
getche()
 getche() is used to get a character from console, and prints to the screen.
 This function reads a character and never waits for Enter key. It just gets processed after the first
key is being pressed.

Declaration:
int getche(void);
Example Declaration:
char ch;
ch = getche();
Return Value:
This function return the character read from the keyboard.
Example Program:
void main()
{
char ch;
ch = getche();
printf("Input Char Is :%c",ch);
}
Program Output:
Input Char Is : A
Working of getche()
 During the program execution, a single character is read through the getche().
 The given value is displayed on the screen and the compiler does not wait for another character to be
typed.
 As soon as a key is pressed, it returns the character to the getche() function and the returned character is
printed through the printf function.

putch()
 Outputs character to the text window on the screen.
Declaration:
int putch(char ch);
Example Declaration:
ch =getch();
putch(ch);
Return Value:
On success, putch() returns the character printed.
On error, it returns EOF.
Example Program:
void main()
{
char ch = 0;
printf("Input a string:");
while ((ch != '\r'))
{
ch = getch();
putch(ch);
}
}
Program Output:
Input a string : welcome
putchar()
 It outputs a single character to the console output(the display screen)
 It is used to display single character.
 putchar is a macro that outputs a character on stdout.
Declaration
int putchar(char c);
Example Declaration
char c;
c = ‘a’;
putchar(c);
Return Value
putchar returns the character that is displayed
Example Program
void main()
{
int c;
c = getchar();
while(c != EOF)
{
putchar(c);
c = getchar();
}
}
Output:
Welcome to C World
Welcome to C World

Note: We can make putc() work similar to the putchar() by specifying the filename as “stdout”. By doing so the
putc() prints the character directly to the console output.

2.8.4.2 String Based I/O Functions


The string based I/O functions are based on a set of characters called as string.
gets()
 gets() gets a string from stdin.
 It Reads a characters from stdin and stores them into a string str until a newline character ('\n') or the
End-of-File is reached.
Declaration:
char *gets(char *s);

Declaration Example
char string[80];
gets(string);
Retrun Value:
On success, gets () returns the string argument s.
On error or end-of-file, gets returns null
Example Program:
void main(void)
{
char string[80];
printf("Input a string:");
gets(string);
printf("The string input was: %s\n", string);
}
Output:
Input a string: Welcome To C
The string input was: Welcome To C

puts()
It prints a string to the standard output
Declaration:
int puts(const char *s);
Remarks:
puts() copies the null-terminated string s to the standard output stream stdout and appends a newline character.
Declaration Example
char string[] = "Hai\n";
puts(string);
Example Program:
void main(void)
{
char string[] = “This is Test\n”;
puts(string);
}
Output:
This is Test

Important Points
gets() Vs scanf()
• gets() - Reads characters from stdin and stores them as a string into str until a newline character ('\n') or
the End-of-File is reached.
• scanf()- Reads data from stdin and stores them according to the parameter format into the locations
pointed by the additional arguments(address).
• gets() read the string values which allows white spaces also.
• scanf() doesn't allow white spaces in string values.

puts() Vs printf()
• printf() returns the number of character written
• puts() returns a non-negative value in case of success.
• In printf() you have to use '\n' to do this.
• puts() moves the cursor to next line.

getch() Vs getche() Vs getchar()


• getch() : Reads a character and never waits for Enter key. it gets processed after any key is pressed and it
never echoes the character on screen which you pressed.
• getche() : it works similar to getch() but it display the character on the screen.
• getchar() : It works differently from the other two. Whenever you press any key the characters are kept in
buffer. After hitting enter the first character gets processed and it is displayed on the screen.
2.9 Decision Making
Decision making” is one of the most important concepts of programming. Programs should be able to make
logical (true/false) decisions based on the conditions. In C programming “selection construct” or “conditional
statement” is used for decision making .
2.9.1 Introduction
 Decision making plays an important role in programming.
 Decision making finds it application in artificial intelligence.
 Decision making is nothing but making a decision among choices.
A program is the execution of sequence of one or more instruction. Usually the sequences of instruction are
executed in the same order they appear. But there will be certain circumstances where user has to make a
decision such as which part of the program should be executed.

Generally every decision making part will have a condition and if the condition is satisfied one part of the
program will be executed otherwise a different part of the program will be executed. The if and else are two
important keywords in decision making.

Types of if else statement


1. The Simple if Statement
2. The if - else Statement
3. The Nested if - else Statement
4. The else-if ladder
Note: any condition can take only two values zero and one. A zero implies that the condition is not
satisfied and one implies that the condition is satisfied.

2.9.2 The Simple if Statement


Definition
If the condition is true, block of statements will be executed.
Syntax
if(condition)
{
Block of statements;
}
Example
if(marks>50)
{
printf(“you passed”);
}
In the above example the program will print “you passed” only if the marks is greater than 50.
Example Program
//Example of if statement
#include<stdio.h>
void main()
{
int age=19;
if(age>=18)
printf("You are Eligible for Vote");
}

Output:
You are Eligible for Vote

2.9.3 The if - else Statement


Definition
If the condition is true, block1 of statements will be executed else block2 of statements will be executed.

Syntax
if(condition)
{
Block1 of statements;
}
else
{
Block2 of statements;
}

Example
if(marks>50)
{
printf(“you passed”);
}
else
{
printf(“you failed”);
}
In the above example the program will print “you passed” only if the mark is greater than 50 else it will print
“you failed”.
Example Program
//Example of if statement
#include<stdio.h>
void main()
{
int age=17;
if(age>=18)
printf("You are Eligible for Vote");
else
printf("You are Not Eligible for Vote");
}
Output:
You are Not Eligible for Vote

Note: Both if and else statements will not end with a semicolon. else statement will not have a condition.
else statement should definitely follow an if statement.
2.9.4 The Nested if Statement
Definition
If the condition1 is true it will check condtion2 and if condition2 is true, it will check condition3…conditionN,
and if all the conditions are true,then the block of statements will be executed.
Syntax
if(condition1)
{
if(condition2)
{
…….
…….
if(conditionN)
{
Block of statements;
}
}
}
Example Program
//Example of Nested if statement
#include<stdio.h>
void main()
{
int a = 100;
int b = 20;
int c = 50
if( a > b )
{
if(a > c)
{
printf("a is the biggest number" );
}
}
}
Output:
a is the biggest number

Note: If any one of the condition in the nested-if structure is not satisfied then the successive conditions
will be skipped and will not be checked.
When we check for an equality condition, double equalto(==) should be used.

2.9.5 The else - if Ladder


Definition
If the condition1 is false, then condition2 is checked and if the condition2 is false then condition3 is checked and
if condition3 is false it continues to check further condition until a condition is satisfied.
It is a conditional statement which is used when we want to check more than condition at a time in a same
program. If the condition is true then it executes the block of statements of true part else it goes to next
condition.
Syntax
if ( condition 1)
{
statement - 1;
}
else if (condtion 2)
{
statement - 2;
}
else if ( condition n)
{
statement - n;
}
else
{
default statment;
}
statement-x;

Example Program
//Example of if else ladder
#include<stdio.h>
void main()
{
int marks = 67;
if(marks = = 100)
{
printf("You got centum");
}
else if(marks > 80)
{
printf("You got A grade");
}
else if(marks > 60)
{
printf("You got B grade");
}
else if(marks > 40)
{
printf("You got C grade");
}
else
{
printf("you failed");
}
getch();
}
Output:
You got B grade
2.9.6 The switch Statement
Introduction
 The switch statement is used to select a particular block of statement among N block of statements for
execution.
 It is also called as multiway decision statement
 A switch statement allows a variable to be tested for equality against a list of values. Each value is called
a case.
 Each case will have a
o test value,
o a block of a statement and
o a break statement at the end.
 Switch statements simulate the use of multiple if statement.

Why we should use Switch Case?


 One of the classic problems encountered in nested if-else / else-if ladder is called problem of
Confusion. It occurs when no matching else is available for if .
 As the number of alternatives increases, the Complexity of program increases drastically.
 To overcome this , C Provide a multi-way decision statement called ‘Switch Statement‘
Syntax
switch(expression)
{
case constant1:
statements 1;
break;
case constant2:
statements 2;
break;
…………………..
default:
statements n;
break;
}
 When the switch statement is executed, the expression in the switch statement is evaluated and the
control is transferred directly to the group of statements whose case label value matches the value of the
expression.
 Each group of statement ends with a break statement.
 The execution of break statement causes immediate exit from the switch statement.
 If break statement is not present, then all the statement following the matched case will be executed.
 If none of the case-label value matches the value of expression, then default case will be executed.
 If none of the case-label value matches the value of expression, and there is no default case then the
control is transferred directly to the statement that follows the switch statement.
Example Program:

//Example of switch case


#include <stdio.h>
#include <stdlib.h>
void main()
{
int input;
do
{
printf( "1. Play game\n" );
printf( "2. Load game\n" );
printf( "3. Play multiplayer\n" );
printf( "4. Exit\n" );
printf( "Selection: " );
scanf( "%d", &input );
switch ( input )
{
case 1: /* Note the colon, not a semicolon */
printf("Playing the game\n");
break;
case 2:
printf("Loading the game\n");
break;
case 3:
printf("Playing multiplayer\n");
break;
case 4:
printf( "Thanks for playing!\n" );
break;
default:
printf( "Bad input!\n" );
break;
}
}while(input != 4);
}
Output:
1. Play game\n
2. Load game
3. Play multiplayer
4. Exita
Selection:1
Playing the game

1. Play game\n
2. Load game
3. Play multiplayer
4. Exit
Selection:2
Loading the game

Some rules in the switch case statement


1. There should be colon (:) and not a semi-colon (;) after the keyword case.
2. any number of case statements can be there within a switch
3. The constant-expression for a case must be the same data type as the variable in the switch,
4. It must be a constant(either integer constant or character constant )
5. The case value can be a expression, but the value of the expression should be an integer
6. No two case values should be identical
7. Break statement after each case is not compulsory, but if it is not given all statements that are followed
by the matched case will be executed.
8. The value of the switch expression is compared with the case value only in the order they appear within
the switch case.
9. Default case is usually given in the last, but it is not necessary.
2.9.7 Nested switch case
 Nested switch case is nothing but a switch case within another switch case.
 The inner switch will be a part of the outer switch.
 The inner and outer switch can have the same case values.
Syntax
switch(outerValue)
{
case value1 :
statement(s);
break;
case value2 :
statement(s);
break;
default :
switch(innerValue)
{
case value1 :
statement(s);
break;
case value2 :
statement;
break;
default:
statement;
break;
}
}
Example:
//Example of Nested switch case
#include <stdio.h>
void main ()
{
/* local variable definition */
int a = 100;
int b = 200;
switch(a)
{
case 100:
printf("This is part of outer switch\n", a );
switch(b)
{
case 200:
printf("This is part of inner switch\n", a );
}
}
}
Output:
This is part of outer switch
This is part of inner switch
2.9.8 switch case Vs else if
switch case else if ladder
It can test only constant values It can evaluate relational and logical expressions
too
Real numbers cannot be used for testing the Real numbers can be used for testing the
condition condition
It can evaluate more than one condition at once It can evaluate more than one condition at once
.
2.10 Branching and Looping
Branching is deciding what actions are to be executed and looping is deciding how many times to a certain
action is to be executed.
2.10.2 Conditional Vs Unconditional Branching
Conditional Branching Unconditional Branching
It evaluates a condition and decides which part It does not evaluate a condition
of the program is to be executed
It simply skips one part of the program and It jumps from one part of the program to another
executes the other part of the program part of the program.
It cannot jump back in a program execution It can jump back in a program execution
It is not difficult to trace the control flow of the It is difficult to trace the control flow of the
program program
Example Example
If statement Goto
.

2.10.3 Unconditional Statement : The goto Statement


• The goto statement is an unconditional jump statement which jumps from one point to another point
within a program.
• The goto statement is associated with a label.
• The program execution will jump to the place where label has been specified
• Label can be used anywhere in the program (above or below the goto statement).
Syntax
goto label;
..........….
...…........
..........….
label:
statement;
Here after reaching the goto ,the compiler searches for the label in the entire program and if the label is found
the program execution starts from the label.
Note: label is just an identifier.

Example of goto statement


/* C program to demonstrate the working of goto statement.*/
# include <stdio.h>
void main()
{
int num,sum=0;
int i,n;
printf("press 0 to stop");
jump2:
printf("Enter a number");
scanf("%d",&num);
if(num==0)
{
goto jump1; /* control of the program jumps to label jump1 */
}
else
{
sum=sum+num;
goto jump2;
}
jump1:
printf("sum: %d", sum);

}
Output:
press 0 to stop:
Enter a number : 5
Enter a number : 4
Enter a number : 3
Enter a number : 2
Enter a number : 1
Enter a number : 0
sum: 15

Note: Though goto statement is included in ANSI standard of C, use of goto statement should be reduced
as much as possible in a program.

Reasons to avoid goto statement


 Using goto statement makes the logic of the program complex and tangled.
 It makes code confusing.
 It makes difficult to trace the control flow of a program, making the program hard to understand and hard
to modify.
 In modern programming, goto statement is considered a harmful construct and a bad programming
practice.
 The goto statement can be replaced in most of C program with the use of break and continue statements.
2.10.4 Introduction to Looping

2.10.5 The for loop


Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied, i.e., for
loops are used in performing repetitive work in programming.

Syntax
for(initialization; condition; increment/decrement)
{
Block of statement;
}
Stepwise execution of for loop:
Step1: A value will be initialized.
Step2: Condition will be checked and if the condition is true then step3,otherwise step 6
Step3: Execute the block of statements
Step4: Increment/Decrement the initialized value
Step5: Goto Step2
Step6: End of for loop

Example:
for(a=10;a<=20;a++)
{
printf(“hai”);
}
In the above example the initial value of the variable a is 10 ,the condition will not be satisfied when the variable
a reaches the value of 21 and so it will come out of the for loop after printing “hai” ten times.
Note :
 For Single Line of Code – Opening and Closing braces are not needed.
 For Loop can be without a body (it just introduces delay).
 For Loop is Entry Controlled Loop.[i.e. conditions are checked and if it is found true, then only code is
executed ]
Program:
Write a program to find the sum of first n natural numbers where n is entered by user.
#include <stdio.h>
void main()
{
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */
}
printf("Sum=%d",sum);
}
Output:
Enter the value of n.
5
Sum=15
Explanation:
Iteration Value Value Value Condition Value of
of of of Count <= N conditional
N count sum Expression
Initially 5 - 0 - -
Iteration1 5 1 1 1 <= 5 TRUE
Iteration2 5 2 3 2 <= 5 TRUE
Iteration3 5 3 6 3 <= 5 TRUE
Iteration4 5 4 10 4 <= 5 TRUE
Iteration5 5 5 15 5 <= 5 TRUE
Iteration6 5 6 15 6<= 5 FALSE

2.10.6 Nested for loop


A for loop within a for loop is called nested for loop.
Syntax
for(initialization; condition; increment/decrement)
{
Block of statements A1;
for(initialization; condition; increment/decrement)
{
Block of statements B;
}
Block of statements A2;
}

Stepwise execution of for loop:


Step1: Value will be initialized for outer loop.
Step2: Condition will be checked and if the condition is true then step3,otherwise step12
Step3: Execute the block of statementsA1 of outer for loop
Step4: Value will be initialized for inner loop
Step5: Condition will be checked and if the condition is true then step6,otherwise step9
Step6: Execute the block of statements B
Step7: Increment/Decrement the initialized value of inner for loop
Step8: Goto Step5
Step9: Block of statements A2.
Step10: Increment/Decrement the initialized value of outer for loop
Step11: Goto Step2
Step12: End outer for loop
Note: For each cycle of the outer loop, the inner loop executes for the entire cycle.

Example Program:
The following program uses a nested for loop to find the prime numbers from 2 to 10:
/* program to demonstrate the working of nested for loop*/
#include <stdio.h>
void main ()
{
int i, j; /* local variable definition */
for(i=2; i<10; i++)
{
for(j=2; j <= (i/j); j++)
{
if(!(i%j))
break; // if factor found, not prime
}
if(j > (i/j))
printf("%d is prime\n", i);
}
}
Output:
2 is prime
3 is prime
5 is prime
7 is prime
2.10.7 The while loop
Syntax:


Initialization;


while(condition)
{
Block of statement;
Increment/decrement;
}
The difference between the for loop and the while loop is that the initialization, condition,
increment/decrement are in a single line in the for loop and it is kept separately in the while loop.

Example
a=10;
while(a>=20)
{
printf(“hai”);
a++;
}

Program
Write a C program to find the factorial of a number, where the number is entered by user. (Hints:
factorial of n = 1*2*3*...*n
/* program to demonstrate the working of while loop*/
#include <stdio.h>
void main()
{
int number,factorial;
printf("Enter a number.\n");
scanf("%d",&number);
factorial=1;
while (number>0)
{
factorial=factorial*number;
--number;
}
printf("Factorial=%d",factorial);
}
Output:
Enter a number.
5
Factorial=120
2.10.8 The do-while loop
In C, do...while loop is very similar to while
loop. Only difference between these two
loops is that, in while loops, test expression is
checked at first but, in do...while loop code is
executed at first then the condition is
checked. So, the code are executed at least
once in do...while loops.
Syntax


Initialization;


do
{
Block of statement;
Increment/decrement;
}while(condition);

Example Program
Write a C program to add all the numbers entered by a user until user enters 0.
/*C program to demonstrate the working of do...while statement*/
#include <stdio.h>
void main()
{
int sum=0,num;
do
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}
while(num!=0); // do..while loop must end with semicolon
printf("sum=%d",sum);
}
Output
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
Note: do..while loop must end with semicolon (;)

2.10.9 while Vs do-while Statements


While do-while
The condition is checked at the beginning The condition is checked at the end
The condition must be initially true The condition need not be initially true
It may or may not be executed at least once It may be executed at least once
It is an entry controlled loop It is an exit controlled loop
.
Break/continue
 These statements break and continue are used to interrupt the normal flow of control of a program.

2.10.10 The break Statement


Introduction
 It is sometimes desirable to skip some statements inside loop and terminate the loop immediately
without checking the test expression. In such cases, break statements are used.
break Statement
In C programming, break is used in terminating the loop immediately after it is encountered. The break
statements are usually used with conditional if statement.
Syntax:
break;
The break statement can be used to terminate all three loops for, while and do...while loops.

The figure below explains the working of break statement in all three type of loops.

Example of break statement


Write a C program to find sum of n positive numbers entered by user.
/* C program to demonstrate the working of break statement by terminating a loop, if user inputs
negative number*/
//Example for break
# include <stdio.h>
void main()
{
int num,sum=0;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i)
{
printf("Enter n%d: ",i);
scanf("%d",&num);
if(num<0)
break; //for loop breaks if num<0.0
sum=sum+num;
}
printf("sum=%d",sum);}
Output:
Maximum no. of inputs
8
Enter n1: 10
Enter n2: 12
Enter n3: 7
Enter n4: -1
sum=29

Explanation
In this program, when the user inputs number less than zero, the loop is terminated using break statement with
executing the statement below it i.e., without executing sum=sum+num.
In C, break statements are also used in switch...case statement.
Note : if statement is not an loop, it’s an conditional statement. So we can’t use break for if statement.
2.10.11 The continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are used.
Syntax
continue;
Just like break, continue is also used with conditional if statement.
For better understanding of how continue statements works in C programming. Analyze the figure below which
bypasses some code/s inside loops using continue statement.

Example of continue statement


Write a C program to find the product of 10 integers entered by a user. If user enters 0 it is skipped.
//program to demonstrate the working of continue statement in C programming
# include <stdio.h>
void main()
{
int i,num,product=1;
for(i=1;i<=10;++i)
{
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
continue; // when num equals to 0, it skips the statement product=product*num and moves to next iteration
product=product*num;
}
printf("product=%d",product);
}

Output:
Enter num1:5
Enter num2:0
Enter num3:4
Enter num4:0
Enter num5:3
Enter num6:0
Enter num7:2
Enter num8:0
Enter num9:1
Enter num10:0
product=120

break Vs continue
The break statement in C completely terminates the execution of the current loop, and processes the
statement which is placed immediately after the loop.
The continue statement just skips the current iteration of the loop and processes the next iteration in the loop.
break continue
When a compiler encounters a break ,the control is When a compiler encounters a continue,the control is
moved to the end of the loop. moved to the beginning of the loop.
It terminates the execution of the loop It terminates the current iteration of the loop
It moves to the statement immediatley after the loop It continues to the next iteration
It skips an entire loop It skips only a particular iteration
Keyword is break Keyword is continue

You might also like