unit-1 Introduction to c
unit-1 Introduction to c
1. Procedural Language
1
2. Fast and Efficient
3. Modularity
4. Statically Type
5. General-Purpose Language
6. Rich set of built-in Operators
7. Libraries with rich Functions
8. Middle-Level Language
9. Portability
10.Easy to Extend
2
Databases: PostgreSQL, Oracle, MySQL, MS SQL Server etc.
Rich set of built-in Operators: It is a diversified language with a rich set of
built-in operators which are used in writing complex or simplified C
programs.
Libraries with rich Functions: Robust libraries and functions in C help even
a beginner coder to code with ease.
History of C:
3
Language Year Developed By
4
A High-Level Language is a computer programming language that uses
English like statements to write the computer instructions. High-level
languages are most widely programming languages because they are easy to
understand to human being.
Here is a list of some important characteristics of high-level languages −
It can be easily interpreted as well as compiled in comparison to low-level
language.
It can be considered as a programmer-friendly language.
It is easy to understand.
It is easy to debug.
It is simple in terms of maintenance.
It requires a compiler/interpreter to be translated into machine code.
It can be run on different platforms.
It can be ported from one location to another.
It is less memory efficient, i.e., it consumes more memory in comparison
to low-level languages.
Examples of high-level languages include C, C++, Java, and Python.
t is widely used.
5
S.No
High-Level Language Low-Level Language
.
Algorithm in C
Algorithm is a step-by-step procedure, which defines a set of instructions to be
executed in a certain order to get the desired output. Algorithms are generally
created independent of underlying languages, i.e. an algorithm can be
implemented in more than one programming language.
Characteristics of an Algorithm:
6
Clear and Unambiguous: The algorithm should be clear and
unambiguous. Each of its steps should be clear in all aspects and must lead
to only one meaning.
Well-Defined Inputs: If an algorithm says to take inputs, it should be well-
defined inputs. It may or may not take input.
Well-Defined Outputs: The algorithm must clearly define what output will
be yielded and it should be well-defined as well. It should produce at least
1 output.
Finite-ness: The algorithm must be finite, i.e. it should terminate after a
finite time.
Feasible: The algorithm must be simple, generic, and practical, such that it
can be executed with the available resources. It must not contain some
future technology or anything.
Language Independent: The Algorithm designed must be language-
independent, i.e. it must be just plain instructions that can be implemented
in any language, and yet the output will be the same, as expected.
Input: An algorithm has zero or more inputs. Each that contains a
fundamental operator must accept zero or more inputs.
Output: An algorithm produces at least one output.Every instruction that
contains a fundamental operator must accept zero or more inputs.
Definiteness: All instructions in an algorithm must be unambiguous,
precise, and easy to interpret. By referring to any of the instructions in an
7
algorithm one can clearly understand what is to be done. Every
fundamental operator in instruction must be defined without any ambiguity.
Finiteness: An algorithm must terminate after a finite number of steps in
all test cases. Every instruction which contains a fundamental operator must
be terminated within a finite amount of time. Infinite loops or recursive
functions without base conditions do not possess finiteness.
Effectiveness: An algorithm must be developed by using very basic,
simple, and feasible operations so that one can trace it out by using just
paper and pencil.
Algorithm Example:
Add two numbers entered by the user
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Flowchart in c:
Flowchart is a graphical representation of an algorithm. Programmers often
use it as a program-planning tool to solve a problem. It makes use of symbols
which are connected among them to indicate the flow of information and
processing.
The process of drawing a flowchart for an algorithm is known as
“flowcharting”.
Symbols Used In Flowchart
8
Indicates the flow of logic
Flow line
connecting symbols.
9
Used to connect the flowch
Off-page Connector
portion on a different page.
Represents a group of
Predefined
statements performing one
Process/Function
processing task.
10
It is very difficult to modify the Flowchart.
Making a flowchart is costly.
Some developer thinks that it is waste of time.
It makes software processes low.
If changes are done in software, then the flowchart must be redrawn
Flowchart Example:
Add two numbers entered by the user.
11
2. Interpreter:
An interpreter is a program that translates a programming language into
a comprehensible language. –
It translates only one statement of the program at a time.
Interpreters, more often than not are smaller than compilers.
It does not require source code It requires source code for later
5
for later execution. execution.
12
S.No. Compiler Interpreter
Character set
A character set is a set of alphabets, letters and some special characters that are
valid in C language.
Alphabets
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
13
C accepts both lowercase and uppercase alphabets as variables and functions.
Digits
0123456789
Special Characters
Special Characters in C Programming
, < > . _
( ) ; $ :
% [ ] # ?
^ ! * / |
- \ ~ +
C Keywords
Keywords are predefined, reserved words used in programming that have
special meanings to the compiler. Keywords are part of the syntax and they
cannot be used as an identifier. For example:
int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in lowercase.
Here is a list of all keywords allowed in ANSI C.
C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
14
default goto sizeof volatile
const float short unsigned
C Identifiers:
C Identifiers are names given to different entities such as constants, variables,
structures, functions, etc. This tutorial describes C Identifiers.
Example:
int money;
double accountBalance;
15
Types of identifiers
o Internal identifier
o External identifier
Internal Identifier
External Identifier
Keyword Identifier
It must be written in a lowercase letter. It can be written in both lowercase and upper
letters.
Its meaning is pre-defined in the c Its meaning is not defined in the c compiler.
compiler.
It does not contain the underscore It can contain the underscore character.
character.
Example:
int main()
{
int a=10;
int A=20;
printf("Value of a is : %d",a);
16
printf("\nValue of A is :%d",A);
return 0;
}
Output:
Value of a is: 10
Value of A is: 20
Datatypes in C:
A data type in C refers to the type of data used to store the information. Each
data type requires different amounts of memory and has some specific
operations which can be performed over it. It specifies the type of data that the
variable can store like integer, character, floating, double, etc. The data type is
a collection of data with values having fixed values, meaning as well as its
characteristics.
17
The data types in C can be classified as follows:
Types Description
Primitive Data Arithmetic types can be further classified into integer and
Types floating data types.
The data types that are derived from the primitive or built-
Derived types
in datatypes are referred to as Derived Data Types.
Different data types also have different ranges up to which they can store
numbers. These ranges may vary from compiler to compiler. Below is a list of
ranges along with the memory requirement and format specifiers on the 32-bit
GCC compiler.
Type Storage Size Value Range
Int (or signed int) 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
Short int(or signed short 2 bytes -32,768 to 32,767
int)
Long(or singed short int) 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
float 4 bytes 1.2E-38 to 3.4E+38 (6 decimal places)
double 8 bytes 2.3E-308 to 1.7E+308 (15 decimal places)
Long double 10 bytes 3.4E-4932 to 1.1E+4932 (19 decimal places)
char(or signed char) 1 byte -128 to 127
unsigned char 1 byte 0 to 255
Integer type:
18
The integer data type in C is used to store the whole numbers without
decimal values.
Octal values, hexadecimal values, and decimal values can be stored in int
data type in C.
the size of the int data type by using the sizeof operator in C.
Unsigned int data type in C is used to store the data values from zero to
positive numbers but it can’t store negative values like signed int.
Unsigned int is larger in size than signed int and it uses “%u” as a format
specifier in C
Range: -2,147,483,648 to 2,147,483,647
Size: 2 bytes or 4 bytes
Format Specifier: %d
Example:
// C program to print Integer data types.
#include <stdio.h>
int main()
{
// Integer value with positive data.
int a = 9;
19
printf("Integer value with positive data: %d\n", a);
printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n", c);
printf("Integer value with an long int data: %ld", d);
return 0;
}
Output:
Integer value with positive data: 9
Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998
Charater Types:
Character data type allows its variable to store only a single character.
The storage size of the character is 1.
It is the most basic data type in C. It stores a single character and requires a
single byte of memory in almost all compilers.
20
Format Specifier: %f
Example:
// C Program to demonstrate use
// of Floating types
#include <stdio.h>
int main()
{
float a = 9.0f;
float b = 2.5f;
// 2x10^-4
float c = 2E-4f;
printf("%f\n",a);
printf("%f\n",b);
printf("%f",c);
return 0;
}
Output:
9.000000
2.500000
0.000200
Double Types
A Double data type in C is used to store decimal numbers (numbers with
floating point values) with double precision
It is used to define numeric values which hold numbers with decimal values
in C.
21
Double data type is basically a precision sort of data type that is capable of
holding 64 bits of decimal numbers or floating points.
Since double has more precision as compared to that float then it is much
more obvious that it occupies twice the memory as occupied by the
floating-point type. It can easily accommodate about 16 to 17 digits after or
before a decimal point.
Range: 1.7E-308 to 1.7E+308
Size: 8 bytes
Format Specifier: %lf
Example:
// C Program to demonstrate
// use of double data type
#include <stdio.h>
int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;
printf("%lf\n", a);
printf("%lf\n", b);
printf("%lf", c);
return 0;
}
Output:
123123123.000000
22
12.293123
2312312312.123123
Format Specifiers:
The format specifiers are used in C for input and output purposes. the compiler
can understand that what type of data is in a variable during taking input using
the scanf() function and printing using printf() function. Here is a list of format
specifiers.
%c Character
%d Signed integer
%f Float values
%g or %G Similar as %e or %E
%i Unsigned integer
%lf Double
23
Format Specifier Type
%o Octal representation
%p Pointer
%s String
%u Unsigned int
%x or %X Hexadecimal representation
%n Prints nothing
%% Prints % character
These are the basic format specifiers. We can add some other parts with the
format specifiers. These are like below −
A minus symbol (-) sign tells left alignment
A number after % specifies the minimum field width. If string is less than
the width, it will be filled with spaces
A period (.) is used to separate field width and precision
Example
#include <stdio.h>
main()
{
char ch = 'B';
printf("%c", ch); //printing character data
//print decimal or integer data with d and i
int x = 45, y = 90;
printf("%d", x);
printf("%i", y);
float f = 12.67;
printf("%f", f); //print float value
24
printf("%e", f); //print in scientific notation
int a = 67;
printf("%o", a); //print in octal format
printf("%x", a); //print in hexa format
char str[] = "Hello World";
printf("%s", str);
printf("%20s", str); //shift to the right 20 characters including the string
printf("%-20s", str); //left align
printf("%20.5s", str); //shift to the right 20 characters including the string, and
print string up to 5 character
printf("%-20.5s", str); //left align and print string up to 5 character
}
Output
B
45
90
12.670000
1.267000e+001
103
43
Hello World
Hello World
Hello World
Hello
Hello
We can use these format specifiers for the scanf() function also in the same
manner. So we can take the input from scanf() like above how we have printed.
Operators and Expressions in c:
C Operators are symbols that represent operations to be performed on one or
more operands. C provides a wide range of operators, which can be classified
into different categories based on their functionality. Operators are used for
performing operations on variables and values.
25
What are Operators in C?
Operators can be defined as the symbols that help us to perform specific
mathematical, relational, bitwise, conditional, or logical computations on
operands. In other words, we can say that an operator operates the operands.
For example, ‘+’ is an operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are
operands. The addition operator tells the compiler to add both of the operands
‘a’ and ‘b’. The functionality of the C programming language is incomplete
without the use of operators.
Types of Operators in C
Arithmetic operators.
Relational operators.
Logical operators.
Assignment operators.
Increment and decrement operators.
Bitwise operators.
Conditional operators.
Special operators.
Arithmetic operator
These operators are used for numerical calculations (or) to perform arithmetic
operations like addition, subtraction etc.
26
Example: Arithmetic Operators:
// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
Relational operators
These are used for comparing two expressions.
27
Operator Description Example a=20,b=10 Output
The output of a relational expression is either true (1) (or) false (0).
Logical Operators
These are used to combine 2 (or) more expressions logically.
They are logical AND (&&) logical OR ( || ) and logical NOT (!)
28
exp1 exp2 exp1&&exp2
T T T
T F F
F T F
F F F
Logical AND(&&)
T T T
T F T
F T T
F F F
Logical OR(||)
exp !exp
T F
F T
Logical NOT(!)
29
#include<stdio.h>
int main ( )
{
int a= 10, b = 20, c= 30;
printf (" %d\n", (a>b) && (a<c));
printf (" %d\n", (a>b) | | (a<c));
printf (" %d\n", ! (a>b));
return 0;
}
Output:
011
Assignment operators
It assigns a value to a variable. The types of assignment operators are −
Simple assignment.
Simple assignment.
30
Output:
10
20
Bitwise operators:
The bitwise operators are the operators used to perform the operations on the
data at the bit-level. When we perform the bitwise operations, then it is also
known as bit-level programming. It consists of two digits, either 0 or 1. It is
mainly used in numerical computations to make the calculations faster.
| Bitwise OR operator
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 1
31
Bitwise AND operator
Bitwise AND operator is denoted by the single ampersand sign (&). Two
integer operands are written on both sides of the (&) operator. If the
corresponding bits of both the operands are 1, then the output of the bitwise
AND operation is 1; otherwise, the output would be 0.
For example,
We have two variables a and b.
a =6;
b=4;
The binary representation of the above two variables are given below:
a = 0110
b = 0100
When we apply the bitwise AND operation in the above two variables, i.e., a&b
, the output would be:
Result = 0100
Program:
#include <stdio.h>
int main()
{
int a=6, b=14; // variable declarations
printf("The output of the Bitwise AND operator a&b is %d",a&b);
return 0;
}
Output
32
Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two integer
operands are written on both sides of the (|) symbol. If the bit value of any of
the operand is 1, then the output would be 1, otherwise 0.
For example,
We consider two variables,
a = 23;
b = 10;
The binary representation of the above two variables would be:
a = 0001 0111
b = 0000 1010
When we apply the bitwise OR operator in the above two variables, i.e., a|b , the
n the output would be:
Result = 0001 1111
Program:
#include <stdio.h>
int main()
{
int a=23,b=10; // variable declarations
printf("The output of the Bitwise OR operator a|b is %d",a|b);
return 0;
}
Output:
33
Bitwise exclusive OR operator
Program:
#include <stdio.h>
int main()
{
int a=12,b=10; // variable declarations
printf("The output of the Bitwise exclusive OR operator a^b is %d",a^b);
return 0;
}
Output:
34
Bitwise complement operator
For example,
If we have a variable named 'a',
a = 8;
The binary representation of the above variable is given below:
a = 1000
When we apply the bitwise complement operator to the operand, then the output
would be:
Result = 0111
Program:
#include <stdio.h>
int main()
{
int a=8; // variable declarations
printf("The output of the Bitwise complement operator ~a is %d",~a);
return 0;
}
Output:
35
Bitwise shift operators
Two types of bitwise shift operators exist in C programming. The bitwise shift
operators will shift the bits either on the left-side or right-side. Therefore, we
can say that the bitwise shift operator is divided into two categories:
o Left-shift operator
o Right-shift operator
Left-shift operator
Where,
In the case of Left-shift operator, 'n' bits will be shifted on the left-side. The 'n'
bits on the left side will be popped out, and 'n' bits on the right-side are filled
with 0.
Example:
Suppose we have a statement:
int a = 5;
The binary representation of 'a' is given below:
a = 0101
36
If we want to left-shift the above representation by 2, then the statement would
be:
a << 2;
0101<<2 = 00010100
Program:
#include <stdio.h>
int main()
{
int a=5; // variable initialization
printf("The value of a<<2 is : %d ", a<<2);
return 0;
}
Output:
Right-shift operator
Where,
37
In the case of the right-shift operator, 'n' bits will be shifted on the right-side.
The 'n' bits on the right-side will be popped out, and 'n' bits on the left-side are
filled with 0.
Example:
Suppose we have a statement,
int a = 7;
The binary representation of the above variable would be:
a = 0111
If we want to right-shift the above representation by 2, then the statement would
be:
a>>2;
0000 0111 >> 2 = 0000 0001
Program:
#include <stdio.h>
int main()
{
int a=7; // variable initialization
printf("The value of a>>2 is : %d ", a>>2);
return 0;
}
Output:
38
Increment Operators are the unary operators used to increment or add 1 to the
operand value. The Increment operand is denoted by the double plus symbol (+
+). It has two types, Pre Increment and Post Increment Operators.
Pre-increment Operator
The pre-increment operator is used to increase the original value of the operand
by 1 before assigning it to the expression.
Syntax:
X = ++A;
39
Input the value of X: 10
Input the value of Y: 15
Input the value of Z: 20
Syntax
X = A++;
In the above syntax, the value of operand 'A' is assigned to the variable 'X'.
After that, the value of variable 'A' is incremented by 1.
Example 2: Program to use the post-increment operator in C
#include <stdio.h>
#include <conio.h>
int main ()
{
// declare integer variables
int x, y, z, a, b, c;
printf (" Input the value of X: ");
scanf (" %d", &x);
printf (" Input the value of Y: ");
scanf (" %d", &y);
printf (" Input the value of Z: ");
scanf (" %d", &z);
// use post-increment operator to update the value by 1
a = x++;
b = y++;
c = z++;
40
printf (" \n The original value of a: %d", a);
printf (" \n The original value of b: %d", b);
printf (" \n The original value of c: %d", c);
Output:
Input the value of X: 10
Input the value of Y: 15
Input the value of Z: 20
Decrement Operator
Decrement Operator is the unary operator, which is used to decrease the original
value of the operand by 1. The decrement operator is represented as the double
minus symbol (--). It has two types, Pre Decrement and Post Decrement
operators.
Pre Decrement Operator
The Pre Decrement Operator decreases the operand value by 1 before assigning
it to the mathematical expression. In other words, the original value of the
operand is first decreases, and then a new value is assigned to the other variable.
41
Syntax
B = --A;
In the above syntax, the value of operand 'A' is decreased by 1, and then a new
value is assigned to the variable 'B'.
Output:
Input the value of X: 5
Input the value of Y: 6
42
Input the value of Z: 7
43
printf (" \n The original value of b: %d", b);
printf (" \n The original value of c: %d", c);
Output:
Input the value of X: 6
Input the value of Y: 12
Input the value of Z: 18
Example 5: Program to perform the pre increment and pre decrement operator
#include <stdio.h>
#include <conio.h>
int main ()
{
// declare integer data type variable
int i, j, x, y;
printf (" Enter the value of i " );
scanf (" %d", &i);
44
printf (" Enter the value of j " );
scanf (" %d", &j);
Example 6: Program to print the post increment and post decrement operator
#include <stdio.h>
#include <conio.h>
int main ()
{
// declare integer data type variable
int i, j, x, y;
45
printf (" Enter the value of i " );
scanf (" %d", &i);
printf (" Enter the value of j " );
scanf (" %d", &j);
It is used to increment the value of a variable by It is used to decrease the operand values by 1.
1.
The increment operator is represented as the The decrement operator is represented as the
double plus (++) symbol. double minus (--) symbol.
46
It has two types: pre-increment operator and Similarly, it has two types: the pre-decrement
post-increment operator. operator and the post-decrement operator.
Pre increment operator means the value of the Pre decrement means the value of the operato
operator is incremented first and then used in decremented first and then assigned in the
the expression. expression.
The post-increment operator means the operand Whereas the post decrement operator means t
is first used in the expression and then performs operand is first used in the expression and the
the increment operation to the original value by performs the decrement operation to the
1. operand's original value by 1.
Syntax for the pre increment operator: X = ++a; Syntax for the pre decrement operator: X = --
Syntax for the post increment operator: X = a+ Syntax for the post decrement operator: X = a
+;
Both operators' works only to the single Both operators' works only to the single opera
operand, not values. not values.
10 + 20 * 30
Operators Associativity is used when two operators of same precedence
appear in an expression. Associativity can be either Left to Right
or Right to Left.
For example: ‘*’ and ‘/’ have same precedence and their associativity
is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”
Operators Precedence and Associativity are two characteristics of
operators that determine the evaluation order of sub-expressions in
absence of brackets
Operators Precedence & Associativity Table
Operator Meaning of operator Associativity
() Functional call Left to right
[] Array element reference
-> Indirect member selection
47
. Direct member selection
! Logical negation Right to left
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
-- Decrement
& Dereference (Address)
* Pointer reference
sizeof Returns the size of an object
(type) Typecast (conversion)
* Multiply Left to right
/ Divide
% Remainder
+ Binary plus(Addition) Left to right
- Binary minus(subtraction)
<< Left shift Left to right
>> Right shift
< Less than Left to right
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal to Left to right
!= Not equal to
& Bitwise AND Left to right
^ Bitwise exclusive OR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional Operator Right to left
= Simple assignment Right to left
*= Assign product
/= Assign quotient
%= Assign remainder
+= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
48
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift
, Separator of expressions Left to right
49