Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

UNIT-I Introduction to C Programming-1

The document outlines the Program Development Cycle, which consists of six phases: Problem Definition, Problem Analysis, Designing, Coding & Documentation, Testing & Debugging, and Maintenance. It also describes various computing environments, such as Personal, Time Sharing, Client-Server, Distributed, Grid, and Cluster Computing Environments, along with classifications of computer languages from low-level to high-level. Additionally, it provides a brief history of the C programming language, its standards, and its significance in modern programming.

Uploaded by

manodhar8888
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

UNIT-I Introduction to C Programming-1

The document outlines the Program Development Cycle, which consists of six phases: Problem Definition, Problem Analysis, Designing, Coding & Documentation, Testing & Debugging, and Maintenance. It also describes various computing environments, such as Personal, Time Sharing, Client-Server, Distributed, Grid, and Cluster Computing Environments, along with classifications of computer languages from low-level to high-level. Additionally, it provides a brief history of the C programming language, its standards, and its significance in modern programming.

Uploaded by

manodhar8888
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Program Development Cycle :

When we want to develop a program using any programming language, we follow a sequence of
steps.
These steps are called phases in program development.
The program development life cycle is a set of steps or phases that are used to develop a program in
any programming language.
Generally, program development life cycle contains 6 phases, they are as follows….

1. Problem Definition
2. Problem Analysis
3. Desgining
4. Coding & Documentation
5. Testing & Debugging
6. Maintenance

1. The first step is to define the problem. In major software projects, this is a job for system analyst,
who provides the results of their work to programmers in the form of a program specification. The
program specification defines the data used in program, the processing that should take place while
finding a solution, the format of the output and the user interface.

2. understand the problem statement i.e., what is our requirment, what should be the input & output
of the problem solution.

3.Program design starts by focusing on the main goal that the program is trying to achieve and then
breaking the program into manageable components, each of which contributes to this goal. This
approach of program design is called top-bottom program design or modular programming. The
first step involve identifying main routine, which is the one of program’s major activity. From that
point, programmers try to divide the various components of the main routine into smaller parts
called modules. For each module, programmer draws a conceptual plan using an appropriate
program design tool to visualize how the module will do its assign job.

Algorithms –
An algorithm is a step-by-step description of how to arrive at a solution in the most easiest way.

Flowcharts –
A flowchart is a diagram that shows the logic of the program

Pseudocode –
A pseudocode is another tool to describe the way to arrive at a solution. They are different from
algorithm by the fact that they are expressed in program language like constructs.

4.Coding the program means translating an algorithm into specific programming language. The
technique of programming using only well defined control structures is known as Structured
programming. Programmer must follow the language rules, violation of any rule causes error.
These errors must be eliminated before going to the next step.

5. After removal of syntax errors, the program will execute. However, the output of the program
may not be correct. This is because of logical error in the program. A logical error is a mistake that
the programmer made while designing the solution to a problem. So the programmer must find and
correct logical errors by carefully examining the program output using Test data. Syntax error and
Logical error are collectively known as Bugs. The process of identifying errors and eliminating
them is known as Debugging.

6.In the final phase, the program is deployed (installed) at the user’s site. Here also, the program is
kept under watch till the user gives a green signal to it.
Even after the software is completed, it needs to be maintained and evaluated regularly. In software
maintenance, the programming team fixes program errors and updates the software.

Computing Environments :

When we want to solve a problem using a computer, the computer makes use of various
devices which work together to solve that problem. There may be a various number of ways to
solve a problem. We use various number of computer devices arranged in different ways to solve
different problems. The arrangement of computer devices to solve a problem is said to be a
computing environment. The formal definition of the computing environment is as follows.

The following are the various types of computing environments.


 Personal Computing Environment
 Time Sharing Computing Environment
 Client Server Computing Environment
 Distributed Computing Environment
 Grid Computing Environment
 Cluster Computing Environment

Personal Computing Environment :


Personal computing is a stand-alone machine. In a personal computing environment, the complete
program resides on the stand-alone machine and executed from the same machine. Laptops, mobile
devices, printers, scanners and the computer systems we use at home, office are the examples for
the personal computing environment.

Time-sharing computing environment:

The time-sharing computing environment is a stand-alone computer in which a single user can
perform multiple operations at a time by using a multitasking operating system. Here the processor
time is divided among different tasks and this is called “Time-sharing”. For example, a user can
listen to music while writing something in a text editor. Windows 95 and later versions of Windows
OS, iOS and Linux operating systems are the examples for this computing environment.
Client-server computing environment :

The client-server environment contains two machines (Client machine and Server machine). These
both machines will exchange the information through an application. Here Client is a normal
computer like PC, Tablet, Mobile, etc., and Server is a powerful computer which stores huge data
and manages the huge amount of file and emails, etc., In this environment, client requests for data
and server provides data to the client. In the client-server environment, the communication between
client and server is performed using HTTP (Hyper Text Transfer Protocol).

Distributed computing environment:


In the distributed computing environment, the complete functionality of the software is not on a
single computer but is distributed among multiple computers. Here we use a method of computer
processing in which different programs of an application run simultaneously on two or more
computers. These computers communicate with each other over a network to perform the complete
task. In a distributed computing environment, the data is distributed among different systems and
that data is logically related to each other.

Grid computing environment :

Grid computing is a collection of computers from different locations. All these computers work for
a common problem. A grid can be described as a distributed collection of a large number of
computers working for a single application.

Cluster computing environment:

Cluster computing is a collection of interconnected computers. These computers work together to


solve a single problem. In a cluster computing environment, a collection of systems work together
as a single system.

Algorithm :

To write a logical step-by-step method to solve the problem is called algorithm, in other words, an
algorithm is a procedure for solving problems. In order to solve a mathematical or computer
problem, this is the first step of the procedure. An algorithm includes calculations, reasoning and
data processing. Algorithms can be presented by natural languages, pseudo code and flowcharts,
etc.

FlowChart :

A flowchart is the graphical or pictorial representation of an algorithm with the help of different
symbols, shapes and arrows in order to demonstrate a process or a program. With algorithms, we
can easily understand a program. The main purpose of a flowchart is to analyze different processes.
Several standard graphics are applied in a flowchart.
Computer Languages :
Generally, we use languages like English, Hindi, etc., to make communication between two
persons. That means when we want to make communication between two persons we need a
language through which persons can express their feelings. Similarly, when we want to make
communication between user and computer or between two or more computers we need a language
through which user can give information to the computer and vice versa. When a user wants to give
any instruction to the computer the user needs a specific language and that language is known as a
computer language.
User interacts with the computer using programs and that programs are created using
computer programming languages like C, C++, Java, etc.,
Every computer programming language contains a set of predefined words and a set of rules
(syntax) that are used to create instructions of a program.

Computer Languages Classification


Over the years, computer languages have been evolved from Low Level to High Level Languages.
In the earliest days of computers, only Binary Language was used to write programs. The computer
languages are classified as follows...

Low Level Language (Machine Language)


Low Level language is the only language which can be understood by the computer. Binary
Language is an example of low level language. Low level language is also known as Machine
Language. The binary language contains only two symbols 1 & 0. All the instructions of binary
language are written in the form of binary numbers 1's & 0's. A computer can directly understand
the binary language. Machine language is also known as Machine Code.
As the CPU directly understands the binary language instructions, it does not requires any
translator. CPU directly starts executing the binary language instructions, and takes very less time to
execute the instructions as it does not requires any translation. Low level language is considered as
the First Generation Language (1GL).
Advantages
 A computer can easily understand the low level language.
 Low level language instructions are executed directly without any translation.
 Low level language instructions require very less time for their execution.

Disadvantages
 Low level language instructions are very difficult to use and understand.
 Low level language instructions are machine dependent, that means a program written for a
particular machine does not executes on other machine.
 In low level language, there is more chance for errors and it is very difficult to find errors,
debug and modify.

Middle Level Language (Assembly Language)


Middle level language is a computer language in which the instructions are created using symbols
such as letters, digits and special characters. Assembly language is an example of middle-level
language. In assembly language, we use predefined words called mnemonics. Binary code
instructions in low-level language are replaced with mnemonics and operands in middle-level
language. But the computer cannot understand mnemonics, so we use a translator called Assembler
to translate mnemonics into binary language. Assembler is a translator which takes assembly code
as input and produces machine code as output. That means, the computer cannot understand middle-
level language, so it needs to be translated into a low-level language to make it understandable by
the computer. Assembler is used to translate middle-level language to low-level language.
Advantages
 Writing instructions in middle level language is easier than writing instructions in low level
language.
 Middle level language is more readable compared to low level language.
 Easy to understand, find errors and modify.

Disadvantages
 Middle level language is specific to a particular machine architecture, which means it is
machine dependent.
 Middle level language needs to be translated into low level language.
 Middle level language executes slower compared to low level language.

High Level Language


High-level language is a computer language which can be understood by the users. The high-level
language is very similar to human languages and has a set of grammar rules that are used to make
instructions more easily. Every high-level language have a set of predefined words known as
Keywords and a set of rules known as Syntax to create instructions. The high-level language is
easier to understand for the users but the computer cannot understand it. High-level language needs
to be converted into the low-level language to make it understandable by the computer. We use
Compiler or interpretor to convert high level language to low level language.
Languages like COBOL, FORTRAN, BASIC, C ,C++, JAVA etc., are the examples of high level
languages. All these programming languages use human understandable language like English to
write program instructions. These instructions are converted to low-level language by the compiler
so that it can be understood by the computer.
Advantages
 Writing instructions in high level language is easier.
 High level language is more readable and understandable.
 The programs created using high level language runs on different machines with little
change or no change.
 Easy to understand, create programs, find errors and modify.

Disadvantages
 High level language needs to be translated to low level language.
 High level language executes slower compared to middle and low level languages.

Understanding Computer Languages


The following figure provides few key points related to the computer languages.

From the above figure, we can observe the following key points...
 The programming languages like C, C++, Java, etc., are written in High-level language
which is more comfortable for the developers.
 High level language is closer to the users.
 Low-level language is closer to the computer. Computer hardware can understand only the
low-level language (Machine Language).
 The program written in high-level language needs to be converted to low-level language to
make communication between the user and the computer.
 Middle level language is not closer to both user and computer. We can consider it as a
combination of both high-level language and low-level language.

Generations of Programming Languages


First Generation: Programs are written as a strings of 0s and 1s which is directly understandable
to computer. It is known as Machine Language. Here all the instructions and data are executed
directly by the CPU. As there is no translation needed, so the execution is quite fast. But it is very
much difficult to understand and memorized such complicated combinations of 0s & 1s for human
beings. It is machine dependent and highly complicated and error prone.
Second Generation: A better understandable language for programmer has been developed than
machine language. This is known as Assembly Language. It is similar to machine language but
easier to programming. Here some meaningful, understandable English like abbreviation are used
instead of binary codes. These abbreviations are known as “Mnemonic”. Here translator is require
to converted machine understandable language.
Third Generation: Instead of mnemonics here statements are used which has much resemblances
with English and mathematics. The main advantages of this languages is that it is not machine
dependent and thus easily portable form one machine to another. It is also known as procedural
language. These language are problem oriented rather than instruction oriented.
Third generation languages are also known as high level languages. They are BASIC,
COBOL, FORTAN, C, etc. Here are also needs a translator to make the computer understand its
own machine language. Basically two type of translator required they are compiler and Interpreter.
The main disadvantages of high level language is slowness i.e. more time required for execution.
Fourth Generation: Fourth generation languages consist of report generators, query languages,
application generators interactive database management programs, etc. This language is non-
procedural. The advantages of this languages is that any non-technical persons can also use these
languages to interact with the computer. They are SQL, FOCUS, NOMAD, Intellect, etc. are some
of examples.
Fifth Generation: The Constraint based language and logical programming languages are fifth
generation languages. It mainly used in research of Artificial Intelligence. They are Prolog,
Mercury, etc. are some of examples.

Introduction:
C is general-purpose procedural programming language developed by Dennis Ritchie at AT&T’s
Bell laboratories in 1972. It is a high-level programming language. However, often referred as a
middle-level programming language; since it provides rich support to low-level programming
constructs.
The development of C began, to re-implement the UNIX operating system. It is such a powerful
language that most of the popular operating systems are completely or partially written in C. It is
mostly used for the development of Operating systems, Kernels, Compilers, Device drivers,
embedded systems, RDBMS packages etc.
C is also called as the mother of all programming languages. Because most of the modern computer
programming languages directly or indirectly influenced from C (such as C++, Java, C#, PHP, Perl,
and JavaScript etc.).
History:

The advent of C programming begin in the late 1960s and share roots deep in the development of
UNIX operating system. UNIX is a popular network operating system that pumps heart of the
modern internet.
In late 1960s Ken Thompson and Dennis Ritchie developed, a language called B. Earlier version of
UNIX uses B programming language. It inherits many of its features from BCPL (Basic Combined
Programming Language).
Later in the early 1970s need for a portable operating system and programming language originated.
Rather developing programs and operating system for a particular machine. The need of a portable
operating system came in existence. This was the period when development of C programming
language started.
During 1969 to 1972, Dennis Ritchie at Bell Laboratories developed C. In 1972, the first release of
C programming got officially public. C inherited many features from ALGOL, BCPL and B. It is
such a powerful language that UNIX operating system is almost completely written in C.
In 1978, it gained huge popularity from the Bell laboratories to the heart of every programmer.
Brain Kernighan along with Dennis Ritchie published the first book on C "The C Programming
Language". The book is popularly also known as "K&R C book”.
C Standards :
The massive popularity of C programming headed development of its versions. However, every
version was similar to the original but often incompatible. To assure the standard of C in every
version, American National Standards Institute (ANSI) initiated work on C standards.
In 1989, ANSI sets base for all implementations of C compilers and published the first standard of
C. The first C standard is popularly known as C89. The current C standard is commonly referred as
C11.

A Computer understands only binary language and executes instructions coded in binary language.
It cannot execute a single instruction given in any other form. Therefore, we must provide
instructions to the computer in binary language. Means we must write computer programs entirely
in binary language (sequence of 0s and 1s).
But think for a while, how cumbersome programming would have been, if we have to write every
program as a sequence of 0s and 1s? It would have been a nightmare to write complex software's.
Humans are good at giving instructions in English language, whereas computers can only process
binary language.
So, there was a need of a translator that translates the computer instructions given in English
language to binary language. Hence, to accomplish the job of a translator compiler was invented.
The world’s first compiler was written by Grace Hopper in 1952 for the A-0 programming
language.
Features :
C is a popular programming language among programmers. It is one of the widely used
programming language in the world.

Simple and Robust


For beginner’s C is the easiest language to
learn. Its simplicity lies in the lesser
number of programming constructs that
can power up any complex system.
However, some concepts of C programming can become nightmare for beginners. C supports a rich
set of built-in library functions and a variety of operators.
Portability
C is a machine independent language. C programs can run on a range of machines that has a C
compiler. Today almost every machine has a minimum C compiler installed on it. Hence, when you
write programs in C you should not worry, whether your program will run on a particular machine
or not. However, C does not supports platform independency as Java.
Modularity
C programs are modular in nature. We can divide C programs to several modules that will combine
in a single module to build the final program.
Extensibility
C language provides a rich set of built-in library function. We can also build our own library
functions and can use them in future. Because of modularization of programs, you can extend your
C programs anytime.
Speed
The compilation and execution of C programs are faster than modern programming languages.
Wide acceptability
C programming is widely known among programmers around the world. Because of its vast
popularity, it is suitable for most of the system projects.

Need of C Programming :
Whether you are beginning your programming life or you have learnt programming. Learning C has
its own importance, below are the few advantages of C, over other programming languages.
 C is a simple language, compared any other modern programming languages. It contains a
lesser number of programming constructs that makes it easy to learn. However, some
concepts of C programming can be a nightmare for beginners.
 Learning C will make you understand how a computer program functions internally.
 Despite being a high-level programming language its ability to provide rich support for low-
level programming separates it from modern programming languages.
 The Backbone of Operating system development is C. Most of the popular OS either fully or
partially written in C.
 C is the main programming language used in Apple iOS apps and OS development as
Objective C. Objective C is the Object Oriented version of C programming.
 C language is widely used for the development of Compilers, Assemblers, Language
Interpreters, Device drivers, Databases, Embedded systems, Server, Game frameworks etc.
 Most of the modern programming languages either directly or indirectly inherited from C.
Therefore, C will definitely help to learn C inherited languages.

Creation & Execution :


To create and execute a C program you require minimum two software's.
1. A text editor (such as Notepad, Notepad++, Gedit, TextEdit, Sublime etc.)
2. A C compiler (Optionally CodeBlocks IDE).
Compiler is a program that checks source code file for syntactical errors and translates the source
file to low-level machine code, if it is error free.

C compiler is reliable, efficient and popular C/C++ compiler among developers. It is open source
and available to download for all most all operating systems. It is pre-installed C compiler in all
UNIX based operating systems.

Basic Structure Of C:
The
first
line
of
the

program is a comment. Comments are non-executable code used to add inline documentation about
the code or program.
Comments in C begin with /* and ends with */. Anything between are not executed by the
compiler.
 #include <stdio.h>

Almost all C program that I will write in this C tutorial series will begin with the statement #include
<stdio.h>.
#include is a pre-processor directive used to do some processing before compilation process. The
include pre-processor directive inserts all contents of stdio.h file at the beginning of our code.
Why it is used here? stdio.h file contains various input output functions. I have used printf()
function to print a text which exists in stdio.h header file. Hence, I must tell the C compiler
explicitly to link printf() function with our program.
If it seems confusing, leave it for now just remember to add this line at the top of every C program.
Pre-processor directives are explained in depth in later sections.
 int main()
A program is a collection of functions and a function is a collection of tasks. To run any program,
we must know the starting function of a program. You may think it as an entry gate to the program.
int main() is a special function that defines starting point of the program. A function is followed by
a pair of opening and closing curly brace { }. It defines body of the function. We write logic of our
program inside body of main i.e. inside
int main()
{
//Here goes your logic
}
printf("Hello world!");
printf() is a C function used to write text on screen. printf() function takes an argument that
specifies what will be printed on screen.

 return 0;
Return statement specifies that a function has finished all its tasks and it will terminate now. Here
return statement is followed by 0. You are free to use any integer instead of 0. Apart from that,
return 0 has special meaning to main function. It specifies that the program has executed
successfully without any error.
Therefore, I have used 0 instead of any other integer value.

Compilation:

Apart from translating source code from high level language to low level language, compiler has
other responsibilities too. After reading source code written in high level language it performs
below operations -
1. Performs a pre-processing of source code. Gather all files required for the source code to
compile.
2. Parses the entire source code. Checks for any syntax errors in the source code.
3. Performs a thorough syntax analysis of the source code. To understand the structure and
semantic of the source code.
4. Optionally translates the source code in an intermediate code known as object code to
enhance the performance.
5. Translates the object code to binary language known as executable code.

The entire C compilation is broken to four stages.


1. Pre-processing
2. Compilation
3. Assembling and
4. Linking

#include <stdio.h>

int main()
{
printf("hi");

The C compilation begins with pre-processing of


source file. Pre-processor is a small software that accepts C source file and performs below tasks.
 Remove comments from the source code.
 Macro expansion.
 Expansion of included header files.
After pre-processing it generates a temporary file with .i extension. Since, it inserts contents of
header files to our source code file. Pre-processor generated file is larger than the original source
file.
To view contents of the pre-processed file open <file-name>.i in your favourite text editor. As in
our case below is an extract of compilation.i file.
# 1 "compilation.c"
# 1 ""
# 1 ""
# 1 "compilation.c"
# 1 "C:/Program Files (x86)/CodeBlocks/MinGW/include/stdio.h" 1 3
# 293 "C:/Program Files (x86)/CodeBlocks/MinGW/include/stdio.h" 3
int __attribute__((__cdecl__)) __attribute__ ((__nothrow__)) fprintf (FILE*, const char*, ...);
int __attribute__((__cdecl__)) __attribute__ ((__nothrow__)) printf (const char*, ...);
int __attribute__((__cdecl__)) __attribute__ ((__nothrow__)) sprintf (char*, const char*, ...);

int __attribute__((__cdecl__)) __attribute__ ((__nothrow__)) scanf (const char*, ...);


int __attribute__((__cdecl__)) __attribute__ ((__nothrow__)) sscanf (const char*, const char*, ...);

...
...
...

int __attribute__((__cdecl__)) __attribute__ ((__nothrow__)) putw (int, FILE*);


# 3 "compilation.c" 2

main()
{
printf("hi");

}
You can notice that the statement #include <stdio.h> is replaced by its contents. Comment before
the #include line is also trimmed.

In next phase of C compilation the compiler comes in action. It accepts temporary pre-processed
<file-name>.i file generated by the pre-processor and performs following tasks.
 Check C program for syntax errors.
 Translate the file into intermediate code i.e. in assembly language.
 Optionally optimize the translated code for better performance.
After compiling it generates an intermediate code in assembly language as <file-name.s> file.
Moving on to the next phase of compilation. Assembler accepts the compiled source code
(compilation.s) and translates to low level machine code. After successful assembling it generates
<file-name.o> (in Linux) or <file-name.obj> (in Windows) file known as object file. In our case it
generates the compilation.o file.

Finally, the linker comes in action and performs the final task of compilation process. It accepts the
intermediate file <file-name.o> generated by the assembler. It links all the function calls with their
original definition. Which means the function printf() gets linked to its original definition.
Linker generates the final executable file (.exe in windows).

CHARACTER SET :

In C language characters are grouped into the following catagories:


1. Letters(all alphabets a to z & A to Z)
2. Digits (0 to 9)
3. Special characters, ( such as colon :, semicolon ;, period ., underscore _, ampersand & etc).
4. White spaces

TOKENS :
A smallest individual unit in C program is known as C Token. Or a basic building blocks for
constructing a program.

Tokens are either keywords, identifiers, constants, variables or any symbol which has some
meaning in C language. A C program can also be called as a collection of various tokens.

Six type of tokens.

1. Keywords
2. Identifiers
3. Constants
4. String
5. Operator
6. Special Characters

KEYWORDS:

1.They are predefined whose meaning already known to the compiler.

2. Each keyword perform a particular task & have different properties

3. We can't change them (or) use them to name something or identifiers.

4. Also known to be as Reserved words

5. Totally there are 32 keywords.

auto double int struct


break else long switch
case enum register typedef
const extern return union
char float short unsigned
continue for signed volatile
default goto sizeof void
do if static while

IDENTIFIER:

An Identifier is a name given to an entity.That entity may be of variable, array, function, structure,
pointer or user defined data in a programming language.

An identifier can be a variable, but not all identifiers are variables.

Char alpha=' a' ;

alpha is name or identifier for the variable that stores character 'a' in it .
RULES FOR AN IDENTIFIER:

1. Variable name must not start with a digit.


2. Variable name can consist of alphabets, digits and special symbols like underscore _.
3. No special characters, such as semicolon ,whitespaces, slash or comma are permitted to be used
in or as Identifier.
4. Keywords are not allowed as variable name.
5. Upper and lower case names are treated as different, as C is case-sensitive, so it is suggested to
keep the variable names in lower.

Valid Identifiers :num, Num, _num, _Num, num1, Num1, _num1, _Num1, _1num, _1Num, _num_,
number_to_add

Invalid Identifiers : 1num, number to add, 1_num, num-to-add, num@

CONSTANTS :

Constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
(OR)
Constant values used within a program are known as Literals. These constant values occupy
memory but do not have any reference like variables
Constants can be of : A. Integer , B. Float , C. Character & D. String.
A. Integer :An integer literal represents integer or numeric values.
In C programming we can specify an integer constant in three ways.
1.Decimal number (base 10).
2. Octal number (base 8).
3.Hexadecimal number (base 16).

Decimal:
Decimal constant is defined using digits between 0-9.
For example: 123.
Octal:
Octal constants is prefixed with 0 followed by digits between 0-7.

 any number begins with 0 must only contain digits between 0-7 otherwise compiler will
report an error on compilation.

 you might think 012 as a decimal constant 12, but it is an octal constant equivalent to 10 (in
decimal).

Hexadecimal:
Hexadecimal constant is prefixed with 0x or 0X following hexadecimal characters
 i.e. digits from 0-9 and characters from a-f or A-F.

For example: 0X1A or 0x1a or 0x1A (in hexadecimal) equivalent to 26 (in decimal).

2. FLOAT OR REAL :Floating point literal represents fractional values.


In C programming a float or real constant is specified either using decimal or using exponential
notation.
Decimal Notation :
In decimal notation real constant is represented as whole number, followed by an optional decimal
point and fractional part. It may be preceded with + or - symbol representing negative or positive
number.
 Valid examples of float constants in decimal notation.
+1, 1.2, -0.4, 0., .3 ,-.3.
Exponential notations are helpful in representing any number with very big or small magnitude.
Numbers such as, 7850000000000 in exponential notation expressed as 7.85e12, 0.0000000000785
expressed as 7.85e-011.
 Valid examples of real constants in exponential notation
0.1e1, 0e-5, 5e25, +5E+10, -5.2e0
 [+/-] <Mantissa> <e/E> [+/-] <Exponent>
In exponential notation real constants are expressed in scientific format specifying mantissa and
exponent. Valid syntax of writing real constant in scientific format.

RULES:
1. Mantissa can be expressed either as decimal or as fractional number.
2. We can use either uppercase or lowercase for exponent sign i.e. E or e.
3. Exponent must be a decimal value.
4. A + or - sign symbol may be prefixed before exponent and mantissa.
5. Spaces are not allowed.

CHARACTER :Character literal represent character values

Character literal is a single character constant enclosed within single quotes. In C programming
character constant occupies single byte space in memory.
There are many ways to represent a character constant in C programming.
 Using character inside single quote. For example, ‘a’ ‘0’ ‘/’ ‘.’ etc.
 Using escape sequence characters. For example, ‘\n’ ‘\a’ ‘\b’ etc.
 Using an integer ASCII representing of a character. For example, 65 in ASCII format is
used to represent ‘A’.
Escape characters :
Escape characters are sequence of characters that are converted to some another character which are
difficult or impossible to print directly. Characters such as new lines, you cannot print a new line
directly in any programming language by hitting enter key. To print new line an special character is
given \n which is later converted to new line by compiler.
An escape character begin with backward slash \ followed by escape character.

Escape character Description


\0 NULL
\a Alert (Beep)
\b Backspace
\e Escape
\f Formfeed (Return)
\n New line
\r Carriage return
\t Horizontal Tab (Eight blank spaces)
\v Vertical Tab
\\ Backslash
\' Single quotes
Escape character Description
\" Double quotes
\? Question mark

ASCII :
ASCII stands for American Standard Code for Information Interchange. It was developed by
ANSI (American National Standards Institute).
It is a set of decimal coded value for all basic printable and non-printable characters. For example -
A is represented as 65 in ASCII standard. Similarly, there exists an integer value to represent every
printable and non-printable character.
ASCII exists in two versions 7-bit ASCII and 8-bit ASCII. The first 7-bit version of ASCII
contains 128 characters (including upper and lower case alphabets, digits, punctuations, special
characters, non-printable and control characters). It uses 7 bit in memory to represent single
character.
Later 7 bit variant of ASCII was extended to 8 bit and is popularly known as Extended ASCII. It
uses 8 bit to represent a character and can represent upto 255 characters.

STRING :

String literal is a sequence of characters enclosed within double quotes.


 String constant occupies (total count of characters + 1) byte space in memory. The
additional 1 byte is used for \0 (NULL) character. A NULL value is added explicitly at the
end of the string to specify termination of the string.
 You can also concatenate string literals using + operator.
Examples of some valid string constants : "I love programming!"
'A' and "A" both looks similar but in real both are different. 'A' is a character constant occupying 1
byte space in memory. Whereas "A" is a string constant and occupies 2 byte space in memory.

Constants are fixed value variables, whose value cannot be altered throughout the execution of
program. The fixed value is known as literal.
You can define a constant for any type. They behave like normal variables expect that they are
readonly (once assigned cannot be modified).
C supports two styles of constant definition.
1. Using const keyword
2. Using #define directive
Declaring constants restrict programmers to alter its value. The compiler looks for change in the
constant variable and report errors if found.

Using const keyword :


A variable declared with const keyword is marked as readonly. The compiler looks for modification
of readonly variables and report errors if found.
Syntax: const <data-type> <constant-name> = <constant-value>;
e.g., const float PI = 3.14159;

#define is a pre-processor directive used to define constants and macros. It defines compile time
constant and guarantees 100% constantness.
Unlike const keyword it does not define any variable and doesn't consumes memory. Rather during
the compilation process, the compiler replaces all occurrence of the defined constant with its literal
value. Hence, it is also called as compile time constant.
Syntax : #define <constant-name> <constant-value>
e.g., #define PI 3.14159
#define PI 3.14159 defines a constant PI with value 3.14159. The pre-processor replaces all
occurrence of PI with 3.14159 before compilation.
Note: It has been a legacy and also considered as a good programming practice to declare constant
variable names in ALL CAPS.

OPERATOR :
Operators are the symbol given to any arithmetical or logical operations.

COMMENTS :
Comment is non-executable line in source code used to describe a piece of code or program.
Comments provides inline documentation of source code and enhances readability of the code. It
describes what a piece of code does.
 Comments are for readers not for compilers. They make source code more developer
friendly.
 The compiler has nothing to do with comments, it is non-executable piece of code.
Therefore, during the compilation process, pre-processor removes all comments from the
source code.
C programming supports two types of commenting style.
1. Single line comments
2. Multi-line comments
1.Single line comments begin with // double forward slash character. Characters following // is
treated as comment and is not executed by the compiler. Single line comments are best suited when
you want to add short detail about a complex code that can be described in a line.
2.Multi-line comments are used to add a detailed description about the code. It begins with /*
character and ends with */.
Characters between /* */ are treated as comments.
NOTE: Multi-line comments can span upto multiple lines. In addition, you can use multi-line
comments for both single as well as multiple line commenting.

DATA TYPES :
Data type specifies the type of data that is stored in memory.
OR
Data type is a system for defining various basic properties about the data stored in memory.
 Properties such as, type of data, range of data, bytes occupied, how these bytes are
interpreted etc.
 For example: int is a data type used to define integer type variables.
int a;
 here a is an integer type variable. It can store numbers from -2,147,483,648 to
+2,147,483,647.
Data types in C is classified in three broad categories.
1. Primitive data type
2. Derived data type
3. User defined data type

1.Primitive Data Type:


C language supports four primitive types - char, int, float, void. Primitive types are also known as
pre-defined or basic data types.
Data type Size Range Description
char 1 byte -128 to +127 A character
-32,768 to 32,767 or
int 2 or 4 byte An integer
-2,147,483,648 to +2,147,483,647
float 4 byte 1.2E-38 to 3.4E+38 Single precision floating point number
void 1 byte void type stores nothing

The size and range of a data type is machine dependent and may vary from compiler to compiler. C
standard requires only the minimum size to be fulfilled by every compiler for each data type. For
example, size of int type varies from compiler to compiler, but it must be at least 2 bytes on every
compiler.

Character type (char):

Any single character value in C is represented using char.


 Size of char type is 1 byte and can store 128 characters.
Example to define char type variable :
char grade = 'A';
In above code grade is defined as a character type variable and can store any character.

Integer type (int):


In C programming int keyword is used to define a number type. Size of int is 2 or 4 bytes (compiler
dependent) and can store values up to -32,768 to 32,767 or -2,147,483,648 to +2,147,483,647.
Example to define int type variable -
int roll = 24;
In above code roll is defined as an integer type variable and can store any number in int range.

Float type (float):


A real type value in C is defined with float or double keyword. float defines a single precision
floating point number that can store 1.2E-38 to 3.4E+38. Whereas double defines a double precision
floating point number that can store 2.3E-308 to 1.7E+308.
 Number of significant digits after decimal point is known as its precision. Precision of float
type is of 6 decimal places and double is of 15 decimal places.
Example to define float type variable -
float percentage = 95.67;
double speed = 2.998e+8;

void type:
As name suggests void internally does not store anything. void keyword is used to define a function
return type or a generic pointer.

Data type Qualifiers


Qualifiers are optional add-on to the basic data types. They are used to alter the behaviour and
property of basic data types yielding new type with new property and behaviour.
There are two types of data type qualifiers in C, size and sign qualifier.
Standard syntax to use a qualifier
[sign-qualifier] [size-qualifier] <basic-data-type>
Example: unsigned short int
Note: Parts in the square brackets [] are optional and parts in angle bracket < > are mandatory.
Size qualifier
Size qualifier in C is used to alter size of a primitive data type. C supports two size qualifier, short
and long.
Size qualifier is generally used with integer type. In addition, double type supports long qualifier.
Syntax to use size qualifier
[size-qualifier] <basic-data-type>

OR

<basic-data-type> [size-qualifier]

Example to use size qualifier


Data type Description
short int Defines min 2 bytes integer
long int Defines a min 4 bytes integer
long double Defines a min 12 bytes double precision floating point number

Rules regarding size qualifier as per ANSI C standard

 Size of short integer type short int is at least 2 bytes and must be less than or equal to the
size of int
 The size of integer type int is at least 2 bytes and must be greater than or equal to the size of
short.
 The size of long integer types long int is at least 4 bytes and must be greater than or equal to
the size of int.
 The precision of long double must be greater than or equal to double. Precision of double
must be greater or equal to the precision of float.

Note: short int may also abbreviated as short and long int as long. But, there is no abbreviation for
long double.
The GCC C compiler supports one more derived integer type long long or long long int. Size of
long long is 8 bytes and can store numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.

Sign qualifier
Sign qualifier in C is used to specify signed nature of integer types. It specifies whether a variable
can hold negative value or not.
Sign qualifiers are used with integer int and character char type.
C supports two sign qualifier, signed and unsigned. signed specifies a variable can hold both
positive as well as negative integers. unsigned specifies a variable will only hold positive integers.
Example to use sign qualifier
signed short int
unsigned long
unsigned char

By default, integer and character types are signed in nature. Hence, using signed keyword is useless.
However, a good programmer will use to explicitly specify signed nature of the variable.

User defined type include array, pointer, structures, unions, enumeration types etc.
note: Size and range of data type is compiler dependent which may vary.
Data type Size Range Description
char
1 byte -128 to 127 A character
signed char
unsigned char 1 byte 0 to 255 A character
short
Short signed integer of
signed short 2 bytes −32,767 to 32,767
minimum 2 bytes
signed short int
unsigned short Short unsigned integer of
2 bytes 0 to 65,535
unsigned short int minimum 2 bytes
int 2 or 4 -32,768 to 32,767 or -2,147,483,648 to An integer (Both positive
signed int bytes 2,147,483,647 as well as negative)
2 or 4 An unsigned integer
unsigned int 0 to 65,535 or 0 to 4,294,967,295
bytes (Positive integer)
long
Long signed integer of
signed long 4 bytes -2,147,483,648 to 2,147,483,647
minimum 4 bytes
signed long int
unsigned long Long unsigned integer of
4 bytes 0 to 4,294,967,295
unsigned long int minimum 4 bytes
long long
long long int -9,223,372,036,854,775,808 to Integer with doubled
8 bytes
signed long long 9,223,372,036,854,775,807 capacity as of long
signed long long int
unsigned long long
Unsigned integer with
unsigned long long 8 bytes 0 to 18,446,744,073,709,551,615 doubled capacity as of long
int
Single precision floating
float 4 bytes 1.2E-38 to 3.4E+38
point number
Double precision floating
double 8 bytes 2.3E-308 to 1.7E+308
point number
12 Double precision floating
long double 3.4E-4932 to 1.1E+4932
bytes point number

Format specifiers :
Format specifiers defines the type of data to be printed on standard output. Whether to print
formatted output or to take formatted input we need format specifiers. Format specifiers are also
called as format string.

Format specifier Description Supported data types


%c Character char
Format specifier Description Supported data types
unsigned char
short
unsigned short
%d Signed Integer
int
long
float
%e or %E Scientific notation of float values
double
%f Floating point float
float
%g or %G Similar as %e or %E
double
%hi Signed Integer(Short) short
%hu Unsigned Integer(Short) unsigned short
short
unsigned short
%i Signed Integer
int
long
%l or %ld or %li Signed Integer long
%lf Floating point double
%Lf Floating point long double
unsigned int
%lu Unsigned integer
unsigned long
%lli, %lld Signed Integer long long
%llu Unsigned Integer unsigned long long
short
unsigned short
%o Octal representation of Integer. int
unsigned int
long
%p Address of pointer to void void * void *
%s String char *
unsigned int
%u Unsigned Integer
unsigned long
short
unsigned short
%x or %X Hexadecimal representation of Unsigned Integer int
unsigned int
long
%n Prints nothing
%% Prints % character
VARIABLE :

In C language, when we want to use some data value in our program, we can store it in a memory
space and name the memory space so that it becomes easier to access it.
The naming of an address is known as variable.
Variable is the name of memory location. & they are changeable, we can change value of a variable
during execution of a program.
A programmer can choose a meaningful variable name.
Example : average, height, age, total etc.

Declaration of variables must be done before they are used in the program.
It tells the compiler what the variable name is & specifies what type of data the variable will hold.
Declaration is more like informing the compiler that there exist a variable with following datatype
which is used in the program.

Defining a variable means the compiler has to now assign a storage to the variable because it will
be used in the program.
SYNTAX: <data-type> <variable-name>;

int a;

can even define multiple variables of same datatype in a single line by using comma to separate
them.
You can also declare more than one variable of same type at once using comma.
<data-type> <variable-name1>, <variable-name2>, ... , <variable-nameN>;
float b, c;

In C it is illegal to declare multiple variables of different type at once. For example, the below
statement is illegal in C and results in compilation error.

int roll, float average, percentage;

Initializing a variable means to provide it with a value. A variable can be initialized and defined in
a single statement

You can also initialize a variable at the time of its declaration. Variable initialized at the time of its
declaration is called as value initialized variable.

int a=10;

At the time of variable definition, the C compiler allocates a block of bytes in memory of certain
type. Initially the allocated memory contains garbage value.
We say the previous state (garbage state) of a memory location, left by program used in past as
garbage value.
<variable-name> = <value-or-expression>;
Where value is a valid C literal of variable-name type.

RULES FOR NAMING A VARIABLE :

1. Variable name must not start with a digit.


2. Variable name can consist of alphabets(a-z , A-Z), digits (0-9) and special symbols like
underscore _.
3. Blank or spaces are not allowed in variable name.No special characters, such as semicolon
whitespaces, slash or comma are permitted to be used in or as Identifier.
4. Keywords are not allowed as variable name.
5. Upper and lower case names are treated as different, as C is case-sensitive, so it is suggested to
keep the variable names in lower
For example name and Name are two different identifiers in C.

Operators :
Operator is a symbol given to an operation that operates on some value. It tells the computer to
perform some mathematical or logical manipulations.
 Such as + is an arithmetic operator used to add two integers or real types.
C language provides a rich set of operators. Operators are classified into following categories based
on their usage.
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bitwise operators
6. Increment/Decrement operator
7. Conditional (Ternary) operator
8. Other operators

Arithematic Operators:
Let us suppose a = 10, b = 5.

Operator Description Example


Arithmetic operator
Arithmetic operator are used to perform basic arithmetic operations.
+ Add two integer or real type. a + b gives 15
* Multiply two integer or real types. a * b gives 50
/ Divide two integer or real types. a / b gives 2
Modulus operator divide first operand from second a % b gives 0 (As 10/5 will have 0
%
and returns remainder. remainder)

Relational Operators : Used to state relation between operands and also to compare them.
2.Used to form conditions.
Relational operators are used to check relation between any two operands.
If value of left operand is greater than right, returns true else returns
> (a > b) returns true
false
If value of right operand is greater than left, returns true else returns
< (a < b) returns false
false
== If both operands are equal returns true else false (a == b) returns false
!= If both operands are not equal returns true else false. (a != b) returns true
If value of left operand is greater or equal to right operand, returns
>= (a >= b) returns true
true else false
If value of right operand is greater or equal to left operand, returns
<= (a <= b) will return false
true else false

Logical Operators :
Logical operators are used to combine two boolean expression together and results a single boolean
value according to the operand and operator used.
Used to combine two expressions. If
((a>=1) && (a<=10)) returns true since (a>=1) is true
&& both operands are true or Non-Zero,
and also (a<=10) is true.
returns true else false
((a>1) || (a<5)) will return true. As (a>1) is true. Since
If any of the operand is true or Non-
|| first operand is true hence there is no need to check for
zero, returns true else false
second operand.
Logical NOT operator is a unary
!(a>1) will return false. Since (a>1) is true hence its
! operator. Returns the complement of
complement is false.
the boolean value.

Bitwise Operator :
Bitwise operator performs operations on bit(Binary level). Lets suppose a = 10, b = 5
a = 0000 1010 (8-bit binary representation of 10)
b = 0000 0101 (8-bit binary representation of 5)
0000 1010
Bitwise AND performs anding operation on two binary bits value. If & 0000 0101
&
both are 1 then will result is 1 otherwise 0. ____________
0000 0000
0000 1010
| 0000 0101
| Bitwise OR returns 1 if any of the two binary bits are 1 otherwise 0.
___________
0000 1111
0000 1010
Bitwise XOR returns 1 if both the binary bits are different else ^ 0000 0101
^
returns 0. ___________
0000 1111
Bitwise COMPLEMENT is a unary operator.It returns the
complement of the binary value i.e. if the binary bit is 0 returns 1 else
returns 0.
~ 0000 1010
~ ___________
The result of complement is 2's complement of a number.
1111 0101
In two's complement form, a negative number is the 2's complement
of its positive number
<< Bitwise LEFT SHIFT operator is unary operator. It shift the binary 0000 1010 << 2
bits to the left. It inserts a 0 bit value to the extreme right of the
= 0010 1000
binary value.
Bitwise RIGHT SHIFT operator is unary operator. It shifts the binary
0000 1010 << 2
>> bits to the right. It inserts a 0 bit value to the extreme left of the
= 0000 0010
binary value.

How to calcualte complement of a number :


0000 1010 (given)

1 (add )

0000 1011

Just place ( -) sign before result i.e., ( - ) 0000 1011 = - 11

0000 1010 (given)

1111 0101 (negate : replace 1's with 0 & 0's with 1)

Find the 2's complement of a number : 1111 0101

1000 1010 (1's complement: replace 1's with 0 & 0's with
1)
1 (add 1)

(2's complement)
1000 1011

1000 1011 (Left most bit i.e., MSB indicates sign value 1 for -ve & 0 for +ve ; - 8)

<< (Left Shift) :

Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Left Shift (2<<3)


0000 0010 – initial value
0000 0100 – 1st shift (2*2) =4
0000 1000 – 2nd shift(4*2) =8
0001 0000 – 3rd shift (8*2)=16

Short cut :
N*2n

>> (Right Shift) :


Right Shift (60>>3)
0011 1100 – initial value
0001 1110 – 1st shift(60/2)=30
0000 1111 – 2nd shift(30/2)=15
0000 0111 – 3rd shift (15/2)=7

Short cut :
N/ 2n

Increment & Decrement :

Increment/Decrement operator is a unary operator used to increase an integer value by 1 or


decrease it by 1. Increment/decrement operator are of two types Postfix and Prefix.
a++ will result to 11
++ Increment operator will add 1 to an integer value.
++a will result to 11
a-- will result to 9
-- Decrement operator will subtract 1 from an integer value.
--a will result to 9

Post increment/decrement (a++/a--) : First it assigns the value and then evalutes operator.

Pre increment / decrement (++a/--a) : First evaluates the operator & then assigns the value.

Assignment Operator:

Assignment operator is used to assign value to a variable. The value is assigned from right to left.
= Assign value from right operand to left operand. a = 10 will assign 10 in a

Compund Assignment Operator :

Syntax : Operand operator = value ;

e.g., a+=, a-= , a*=, a<<=,a>>=......,

a+=1 equivalent to a=a+1

Conditional Operator:

Ternary operator as a conditional operator and is similar to simple if-else. It takes three operand.
It is used as conditional operator. Syntax b = (a>1) ? a : b;
?: of using ternary operator: will store the value 10 in b as (a>1) is true hence true
(condition) ? (true part) : (false part) part will execute, assigning the value of a in b.

Special Operators ( Sizeof , comma / seperator (,) , addressof (&) )

Comma / seperator : used to distinguish among / seperate variables , constants & arguments /
parameters .

Addressof (&) : used to get the address location of variable .

Sizeof():
Size of a data type is machine dependent and vary from compiler to compiler. However, in
programming there exists situations when we need to know total bytes a type occupies in memory.
To find exact size of a type in C programming we use
sizeof() operator.
 sizeof() is a special operator used to find exact size of a type in memory. The sizeof()
operator returns an integer i.e. total bytes needed in memory to represent the type or value or
expression.
 The sizeof() is much used operator by programmers. It is very useful for developing portable
programs.

SYNTAX:

operator can be used in various way.


sizeof(type)
sizeof(variable-name)
sizeof(expression)

#include <stdio.h>

main()
{
int variable;

// sizeof(type)
printf("Size of char = %d\n", sizeof(char));

// sizeof(variable-name)
printf("Size of int = %d\n", sizeof(variable));

// sizeof(expression)
printf("Size of expression (3+2.5) = %d\n", sizeof(3 + 2.5));

Output:

Size of char = 1
Size of int = 4
Size of expression (3+2.5) = 8 { All operands of expression is promoted to higher type i.e. double
type (since 2.5 is of double type). Hence the expression sizeof(3 + 2.5) is equivalent to
sizeof(double)}

So,the expression doesn't evaluate in the sizeof operator.It gives the bytes consumed by that value
based on its data type.

There are two ways to find minimum and maximum range of a type. You can use any of the
approach to get range of a type.

The minimum and maximum range of a signed type is given by -


-(2N-1) to 2N-1 - 1

(Where N is sizeof(type) * 8 i.e. total number of bits used by the type)


The minimum and maximum range of an unsigned type is given by -

0 to (2N-1) + (2N-1 -
1)

Expression:
Expression is a combination of one or more operators, variables and literals. Each expression
evaluate to a value of a (data) type.
Expression could be as simple as sum of two numbers
sum = num1 + num2

Basic Input & Output Functions :


Input, process and output processed data is the main goal of every computer program. A program
without data is a useless program.
In this post we will learn some basic C functions to input and output value of a variable.
C provides a header file stdio.h (Standard Input Output) that contains various Input/Output
functions. In order to perform any I/O operation you must add an include statement at the top of
your C code.
#include <stdio.h>
scanf() is a versatile function to read input from standard input device (keyboard). It can input any
primitive or derived type.

scanf("format-specifiers", var1-memory-address, ... , varN-memory-address);

scanf() accepts a string containing list of format specifiers. Format specifier is a special string
starts with % symbol, followed by a character. It directs scanf() or printf() function to input or
output a variable value of some type.
For example - %d is a format specifier that tells scanf() to read an integer value. %f is used for float.
Likewise there are lot of format specifiers for different types.
Next parameter, var1-memory-address directs scanf() to store the input value to some memory
location (variable). Here we provide a list of variables to store input data. The variable type should
be compatible with mentioned format specifier. In addition, scanf() accepts variable memory
address not variable name. Hence, we must prefix variable names with & symbol.
We use & (address operator) to get actual memory address of any variable.
e.g., scanf("%d%d", &num1, &num2); // store the values specified by user in variables
num1,num2.
%d tells scanf() function to read an integer variable and store in num1. Similarly, second %d also
tells scanf() to read integer value and store in num2.
Finally, in the statement printf("Sum = %d", sum); Sum = is printed as it is as a simple message.
Next, after printf() encounters format specifier %d. It replaces %d with the value of sum, which
finally prints sum .
printf() :
We use printf() function to print/display output on console (monitor).
printf("format string containing format-specifiers", variable_list);

printf() function accepts a format string as first parameter. Format string contains string or message
we want to print on screen. Optionally, it may contain format specifiers in case we need to print
variable value.
printf() replaces all occurrence of format specifiers with the variable value. Optionally it typecasts a
variable value to specifier type if needed.

e.g., printf("Enter two numbers: ");

e.g., int a=2;


printf(“%d”, a); // to display the value that is stored in a variable.

e.g., printf("Sum = %d", sum);

Type Casting :

Typecasting is a way to convert variables, constants or expression from one type to another type.
Conversion from one type to another is often required in programming.

C supports two types of typecasting -


1. Implicit typecasting
2. Explicit typecasting

Implicit Typecasting:

Implicit typecast is automatic type conversion done by the compiler. Compiler automatically
handles data type conversion. It converts variables and constants of lower type to higher type
whenever required.
The automatic type conversion done by the compiler uses integer promotion rule.
Integer promotion
Compilers are smart at optimizing code for better performance. In the process of code optimization,
the C compiler will perform integer promotion. The compiler
automatically converts all operands to a common type (higher
type used in expression). The process of converting a lower type
to higher is known as integer promotion.
main()
{
char ch = 'A';
int val = ch + 10; /* char ch is promoted to int before addition */

printf("val = %d", val);

}
In the above program char is automatically converted to higher type int before performing addition.
Important note: Implicit conversion may result in data or sign loss. For example - when promoting
long long to unsigned long long negative sign is lost. Also while promoting unsigned long long to
float you may lose data.
Hence, it is often recommended to cast explicitly.

Explicit Typecasting :

Explicit typecasting is manual type conversion from one type to another type. In explicit cast we
have full control over the conversion. Explicit conversion can be performed bi-directional i.e. you
can cast both a lower type to higher as well as a higher type to lower.
Syntax : (typecast) <variable-expression-literal>

Where typecast is a valid C data type.

#include <stdio.h>

int main()
{
int num1, num2, num3;
float average;
num1 = 91;
num2 = 85;
num3 = 83;

average = (float)(num1 + num2 + num3) / 3;

printf("Average = %f", average);

return 0;
}

Average of 91, 85 and 83 is 86.33. But our program shows 86. (num1 + num2 + num3) / 3, all
variables and literals are integer type. Hence, integer division is performed instead of float division.

we must typecast one of the operands to float. In the expression (float) (num1 + num2 + num3) / 3.
Parenthesis and typecast operator has highest precedence. Hence, first sum of num1 + num2 +
num3 is evaluated and converted to float type. Then after division is performed.
So to overcome the above integer division, we must typecast the expression to float type.

Explicit typecasting can also result in data loss. Conversion from float to int will lose decimal part.

Control Statements :

Every program by default execute sequentially. Each and every statement is executed one after
other. However, there happen situations when you need to execute statement/s based on conditions.
Such as display confidential files only if user has authentic credentials.
You may come across situation when you need to execute set of statements repeatedly. Such as
send offer email to all clients.
Control statements in programming handles such situations. Control statement is divided in three
categories.

Decision statement:

Decision statement is condition based statement. It define single or set of conditions that must be
satisfied before statement/s can execute. For example, allow amount withdrawal from ATM, only if
pin validation succeeds. These situations are handled using decision statements.
Decision statements are also known as conditional or branching statement. In decision statement
we will learn about -
 Simple if statement
 if...else and if...else...if statement
 Nested if...else statement
 Switch...case

if :
if statement allows us to select an action based on some condition. It gives programmer to take
control over a piece of code. Programmer can control the execution of code based on some
condition or user input. For example - if user inputs valid account number and pin, then allow
money withdrawal.
If statement works like "If condition is met, then execute the task". It is used to compare things and
take some action based on the comparison. Relational and logical operators supports this
comparison.
If statement perform action based on boolean expression true or false.
A C expression that evaluates either true or false is known as Boolean expression. However, in C
programming there is no concept of true or false value.
In C we represent true with a non-zero integer and false with zero. Hence, in C if an expression
evaluates to integer is considered as Boolean expression.
Syntax :
if(condition/ boolean expression)
{
// body of if
}
In above syntax if boolean expression evaluates true, then statements inside if body executes
otherwise skipped.

Example:
Write a program to input user age and check if he is eligible to vote in India or not. A person in
India is eligible to vote if he is 18+.
#include <stdio.h>

main()
{
/* Variable declaration to
store age */
int age;

/* Input age from user */


printf("Enter your age: ");
scanf("%d", &age);

/* Use relational operator to


check age */
if(age >= 18)
{
/* If age is greater than
or equal 18 years */
printf("You are eligible
to vote in India.");
}

If there is only single statement inside if body, then braces { } are optional. However, braces after if
statement is mandatory, when body of if contains more than one statement.
So, you can write an if condition in two ways.
Syntax :if(condition /boolean_expression)
// Single statement inside if
Syntax: if(condition /boolean_expression)
{
// Statement 1
// Statement 2
...
...
// Statement n
}
There may happen situations when you want to perform single task inside if. For example - If it is
Saturday or Sunday, then employee should not login today. If a student got more than 80 marks,
then he passed with distinction. In such situations you can ignore braces {}.
if...else :
Simple if works as "if some condition is true then do some tasks". It doesn't specifies what to do if
condition is false. A good program must think both ways. For example - if user inputs correct
account number and pin, then allow money withdrawal otherwise show error message to user.
if...else statement is an extension of simple if. It works as "If some condition is true then, do some
task otherwise do some other task".

Syntax :
if(boolean_expression)
{
// Body of if
// If expression is true then execute this
}
else
{
// Body of else
// If expression is false then execute this
}
In above syntax if the given Boolean expression is true then, execute body of if part otherwise
execute body of else part. In any case either body if or body of else is executed. In no case both the
blocks will execute.

Example:
Write a program based on if...else statement. Write a program to input two numbers from user. Print
maximum between both the given numbers.

#include <stdio.h>

main()
{
/*

Declare two integer variables */


int num1, num2;

/* Input two number from user */


printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);

/* Compare both number using relational


operator */
if(num1 > num2)
{
/* If first number is greater than second */
printf("First number is maximum.");
}
else
{
/* If first number is not greater than
second */
printf("Second number is maximum.");
}

Output :
Enter two numbers: 10
20
Second number is maximum.
if..else..if :
Simple if statement gives ability to execute tasks based on some condition. Its extension if...else
takes both sides of the condition and execute some statements if conditions is true or if the
condition is false then, execute some other statement.
If I have at least $1500, then I will purchase Microsoft Surface Pro 4.
Else if I have at least $1200, then I will purchase Apple Mac book Air.
Else if I have at least $1000, then I will purchase HP ultra-book.
Else I will purchase some mid-level developer laptop.
In the above scenario each condition is dependent on parent condition and must be checked
sequentially. Also if a condition is true then all other conditions must be ignored. These situations in
C programming are handled using a combination of if...else...if statement.
if...else...if is an extension of if...else statement. It specifies "If some condition is true then execute
some task; otherwise if some other condition is true, then execute some different task; if none
conditions are true then execute some default task."
Syntax:
if (boolean_expression_1)

{
// If expression 1 is true then execute
// this and skip other if
}
else if (boolean_expression_2)
{
// If expression 1 is false and
// expression 2 is true then execute
// this and skip other if
}
else if (boolean_expression_n)
{
// If expression 1 is false,
// expression 2 is also false,
// expression n-1 is also false,
// and expression n is true then execute
// this and skip else.
}
else
{
// If no expressions are true then
// execute this skipping all other.
}

Example:
#include <stdio.h>

main()
{
/* Declare integer variable */
int num;

/* Input an integer from user */


printf("Enter any number: ");
scanf("%d", &num);

if(num < 0)
{
/* If number is less than zero, then it is negative */
printf("NUMBER IS NEGATIVE.");
}
else if(num == 0)
{
/* If number equal to 0, then it is zero */
printf("NUMBER IS ZERO.");
}
else
{
/* If number is greater then zero, then it is positive */
printf("NUMBER IS POSITIVE.");
}

Output :
Enter any number: -22
NUMBER IS NEGATIVE.
Nested if ..else :
Simple if and if...else...if statements provide a great support to control programs flow. Simple if is
single condition based task i.e. "if some condition is true, then do the task". In contrast if...else...if
statement provides multiple condition checks i.e. "if some condition is true, then do some task. If
the condition is false, then check some other condition and do some task. If all conditions fails, then
do some default task."
Consider a situation, where you want to execute a statement based on multiple levels of condition
check. For example - At airport there are multi-levels of checking before boarding. First you go for
basic security check, then ticket check. If you have valid ticket, then you go for passport check. If
you have valid passport, then again you will go for security check. If all these steps are completed
successfully, then only you can board otherwise actions are taken by the authority.
Nested if...else statements has ability to control program flow based on multiple levels of condition.
Syntax:
if (boolean_expression_1)
{
if(nested_expression_1)

{
// If boolean_expression_1 and
// nested_expression_1 both are true
}
else
{
// If boolean_expression_1 is true
// but nested_expression_1 is false
}
// If boolean_expression_1 is true
}
else
{
if(nested_expression_2)
{
// If boolean_expression_1 is false
// but nested_expression_2 is true
}
else
{
// If both boolean_expression_1 and
// nested_expression_2 is false
}

// If boolean_expression_1 is false
}

Example:
#include <stdio.h>
main()
{
/* Declare three integer variables */
int num1, num2, num3;

/* Input three numbers from user */


printf("Enter three numbers: ");
scanf("%d%d%d", &num1, &num2,
&num3);

if(num1 > num2)


{
if(num1 > num3)
{
/* If num1>num2 and
num1>num3 */
printf("Num1 is max.");
}
else
{
/* If num1>num2 but
num1<num3 */
printf("Num3 is max.");
}
}
else
{
if(num2 > num3)
{
/* If num1<num2 and
num2>num3 */
printf("Num2 is max.");
}
else
{
/* If num1<num2 and
num2<num3 */
printf("Num3 is max.");
}
}

}
Output of the above program
Enter three numbers: 10
20
30
Num3 is max.

user inputs three numbers as num1=10, num2=20 and num3=30.


 The first outer if condition if(num1 > num2) is false since 10 > 20 is false. Hence, outer if
statement is skipped, executing the outer else part.
 Inside the outer else, condition if(num2 > num3) is also false, since 20 > 30 is false. Hence,
the inner if statement is skipped, executing inner else part.
 Inside the inner else there is nothing much to do. Just a simple printf() statement, printing
"Num3 is max."
Switch:
if...else statement provides support to control program flow. if statement make decisions based on
conditions. It selects an action, if some condition is met. However, there exits situations where you
want to make a decision from available choices. For example - select a laptop from available
models, select a menu from available menu list etc.
switch...case statement gives ability to make decisions from fixed available choices. Rather making
decision based on conditions. Using switch we can write a more clean and optimal code, that take
decisions from available choices.
Syntax:
switch(expression)
{
case 1:
/* Statement/s */
break;
case 2:
/* Statement/s */
break;
case n:
/* Statement/s */
break;
default:
/* Statement/s */
}

Expression inside switch must evaluate to integer, character or enumeration constant. switch...case
only works with integral, character or enumeration constant.
 The case keyword must follow one constant of type evaluated by expression. The case along
with a constant value is known as switch label.
 You can have any number of cases.
 Each and every case must be distinct from other. For example, it is illegal to write two case
1 label.
 You are free to put cases in any order. However, it is recommended to put them in ascending
order. It increases program readability.
 You can have any number of statement for a specific case.
 The break statement is optional. It transfers program flow outside of switch...case. break
statement is covered separately in this C tutorial series.
 he default case is optional. It works like an else block. If no cases are matched then the
control is transferred to default block.
Example:
int num = 2;

switch(num)
{
case 1: printf("I am One");
break;
case 2: printf("I am Two");
break;
case 3: printf("I am Three");
break;
default: printf("I am an integer. But, definitely I am not 1, 2 and
3.");
}

 Initially I declared an integer variable num = 2.


 switch(num) will evaluate the value of num to 2.
 After switch(num) got evaluated, switch knows the case to transfer program control.
 Instead of checking all cases one by one. It transfers program control directly to case 2. If
value of num is not matched with any case then switch transfers control to default case, if
defined.
 After the control has been set to case 2. It executes all statements inside the case. The case
contains two statement first printf("I am Two"); and second break. printf("I am Two"); will
print "I am Two" on console and transfers control to break.
 break statement terminates switch...case and transfer program control to statement after
switch.
What if I don’t use break keyword? If you don’t use break keyword, it executes all below
cases until break statement is found. It doesn’t matter whether the remaining case matches or
not, it will execute all below case from matching case in the absence of break keyword.

Use if...else...if statement when -


 There are conditions instead of list of choices.
 There are few number of conditions.
Use switch...case when -
 There is a list of choices, from which you need to take decision.
 Choices are in the form of integer, character or enumeration constant.

NOTE :
switch...case work only with integer, character and enumeration constant.
 The case label must follow a constant. It does not work with variables and expressions.
Remember programs written using switch...case can be transformed to if...else...if. But not all
if...else...if programs can be converted to switch...case.

Iterative statement :
Looping statement defines a set of repetitive statements . These statements are repeated, with same
or different parameters for a number of times.
In programming, there exists situations when you need to repeat single or a group of statements till
some condition is met. Such as - read all files of a directory.
Looping statements are also known as iterative or repetitive statement.
There are three types of looping statement in C.
 for loop
 while loop
 do...while loop
for :
when we need to perform a set of task repeatedly till some condition is met. Such as – sending
email to all employees, deleting all files, printing 1000 pages of a document. All of these tasks are
performed in loop. To do such task C supports looping control statements.
For loop is an entry controlled looping statement. It is used to repeat set of statements until some
condition is met.
Looping statements whose condition is checked prior to the execution of its body is called as Entry
controlled loop.

Syntax:
for(variable-initialization ; condition ; variable-update)
{
// Body of for loop
}

Any repetition contain two important part - What to repeat and


number of repetition? variable-initialization, condition and
variable-update define number of repetition and body of loop
define what to repeat.

 Variable-initialization contain loop counter variable


initialization statements. It define starting point of the
repetition (where to start loop).
 Condition contain boolean expressions and works like
if...else. If boolean expression is true, then execute body
of loop otherwise terminate the loop.
 Body of loop specify what to repeat. It contain set of
statements to repeat.
 Variable-update contains loop counter update (increment/decrement) statements.
Important note: All four parts of a for loop is optional. Hence you can write a for loop without
initialization, condition, update or body. However, you must follow the syntax and specify
semicolons.
How it works :
1. Initially variable-initialization block receive program control. It is non-repeatable part and
executed only once throughout the execution of for loop. After initialization program control
is transferred to loop condition.
2. The loop condition block evaluates all boolean expression and determines loop should
continue or not. If loop conditions are met, then it transfers program control to body of loop
otherwise terminate the loop. In C we specify a boolean expression using relational and
logical operator.
3. Body of loop execute a set of statements. After executing all statements it transfer program
control to variable-update block.
4. Variable-update block updates loop counter variable and transfer program control again
back to condition block of loop.
Step 2 to 4 is repeated until condition is met.
Example:
#include <stdio.h>

main()
{
/* Declare loop counter variable */
int count;

/* Run a loop from 1 to 10 */


for(count=1; count<=10; count++)
{
/* Print current value of count */
printf("%d ", count);
}

Output :
1 2 3 4 5 6 7 8 9 10

While :

for loop is easy to implement if you specifically know start and end position of the loop counter.
However, things in the real life are not so simple. You may come across situation where you only
know when to terminate the loop. For example – reading instructions from user until terminated
manually, waiting for client connection until connected or cancelled, reconnecting to the server
until connected.
while loop is an entry controlled looping construct. We use while loop to repeat set of statements
when number of iterations are not known prior to its execution. It provides flexibility to define loop
without initialization and update parts (present in for loop).
Looping statements whose condition is checked prior to the execution of its body is called as Entry
controlled loop.

Syntax:
while(condition)
{
// Body of while loop
}

Unlike for loop, while does not contain initialization and update part. It contains only two parts -
condition and body of loop.
 condition is a boolean expression evaluating an integer value. It is similar to if...else
condition and define loop termination condition.
 Body of loop contains single or set of statements. It define statements to repeat.
initialize loop counter variables anywhere in the program before its use. However, best practice is to
initialize all important loop variable just before the loop. Likewise, you can keep your loop update
part just before the end of loop.

How it Works ?
Simplicity of while loop exists in its working mechanism. while loop works in two steps.
1. Initially program control is received by condition block. It contains set of relational and
logical expressions. If result of the conditional expression is 1 (true) then while transfers
program control to body of loop. Else if result of conditional expression is 0 (false) then it
exits from loop.
2. Body of loop contain single or set of statements to repeat. It execute all statements inside its
body and transfer the program control to loop condition block.
Step 1 and 2 are repeated until the loop condition is met.
The above two steps are repeated, until loop condition is true.

Example:

#include <stdio.h>

main()
{
/* Loop counter variable declaration and
initialization*/
int n = 1;

/* Loop condition */
while(n <= 10)
{
/* Body of loop */
printf("%d ", n);

/* Update loop counter variable */


n++;
}

}
Output -
1 2 3 4 5 6 7 8 9 10

 The statement int n = 1; declares a loop counter variable initialized with 1.


 Next loop condition receives program control and check condition n <= 10, which is true,
hence while transfers program control to loop body.
 Inside loop body statement printf("%d ", n); displays the current value of n i.e. 1 on console.
 The statement n++; increment the value of n by 1. Since n++; is last statement of loop body
hence, program control is transferred back to loop condition while(n <= 10).
 Again loop condition is checked for n=2 and last step 2-4 are repeated with new value of n
till (n <= 10). Once n = 11, the loop condition while(n <= 10) gets false and loop terminate.
do while :

C programming supports three types of looping statements for loop, while loop and do...while loop.
Among three do...while loop is most distinct loop compared to others.
do...while is an exit controlled looping statement. We use do...while loop when there is a need to
check condition after execution of loop body. do...while loop in any case executes minimum once.
Looping statements whose condition is checked after execution of its loop body is called as Exit
controlled loop
We use do...while loop if we need to execute loop body minimum once. For example - consider a
program to validate user input and run in loop until user feeds valid input. In this case the input
statement should run minimum once and should repeat in loop until user provides valid input.
Syntax:
do
{
// Body of do while loop
} while (condition);

Similar to while, do...while loop contains two parts -


body of loop and loop condition.
 Body of loop contains single or set of statements
to repeat.
 The loop condition is a boolean expression
evaluating to an integer value. If loop condition
is true then loop repeats otherwise terminates.
Similar to while you can put loop counter variable-
initialization statement before loop and variable-update before end of do...while loop.
Unlike other two loops do...while contain semicolon at the end.
How It Works ?

do...while loop works in two step.


1. Initially program control transfers to body of loop. It executes all statements inside loop
body and transfers control to loop condition.
2. Loop condition contains set of relational and logical expressions. If conditional expression
evaluates 1 (true) then loop repeats again otherwise if conditional expression evaluates 0
(false) loop terminates.
The above two steps are repeated until loop condition is met.
Example:
#include <stdio.h>

main()
{
/* Loop counter variable declaration */
int n=1;

do
{
/* Body of loop */
printf("%d ", n);
/* Update loop counter variable */
n++;

} while(n <= 10); /* Loop condition */

Output -
1 2 3 4 5 6 7 8 9 10
Explanation :
 The statement int n=1; declares an integer loop counter variable initialized with 1.
 Next program control directly enters in loop body and executes the statement printf("%d ",
n);. It print current value of n i.e. 1 for first run.
 The statement n++; increments the value of n by 1.
 Finally, loop condition part receives program control. Inside loop condition it evaluates (n
<= 10). If the statement is true then the loop will continue otherwise terminate. For now it
checks with n=1 i.e. while(1 <= 10); which is true hence loop continues.
 In next iteration it prints 2 and increment n again by 1. Finally checks the loop condition
while(n <= 10); which is again true.
The above 2-4 steps are repeated till condition is true.

You might also like