UNIT-I Introduction to C Programming-1
UNIT-I Introduction to C Programming-1
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 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).
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.
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.
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.
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.
Disadvantages
High level language needs to be translated to low level language.
High level language executes slower compared to middle and low level 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.
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.
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.
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.
#include <stdio.h>
int main()
{
printf("hi");
...
...
...
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 :
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.
1. Keywords
2. Identifiers
3. Constants
4. String
5. Operator
6. Special Characters
KEYWORDS:
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.
alpha is name or identifier for the variable that stores character 'a' in it .
RULES FOR AN IDENTIFIER:
Valid Identifiers :num, Num, _num, _Num, num1, Num1, _num1, _Num1, _1num, _1Num, _num_,
number_to_add
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).
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 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.
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 :
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.
#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
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.
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.
OR
<basic-data-type> [size-qualifier]
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.
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.
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.
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.
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.
1 (add )
0000 1011
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)
Short cut :
N*2n
Short cut :
N/ 2n
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
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.
Comma / seperator : used to distinguish among / seperate variables , constants & arguments /
parameters .
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:
#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.
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
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.
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.
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 */
}
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>
#include <stdio.h>
int main()
{
int num1, num2, num3;
float average;
num1 = 91;
num2 = 85;
num3 = 83;
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;
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()
{
/*
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;
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;
}
Output of the above program
Enter three numbers: 10
20
30
Num3 is max.
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.");
}
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
}
main()
{
/* Declare loop counter variable */
int 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);
}
Output -
1 2 3 4 5 6 7 8 9 10
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);
main()
{
/* Loop counter variable declaration */
int n=1;
do
{
/* Body of loop */
printf("%d ", n);
/* Update loop counter variable */
n++;
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.