C Language
C Language
C is a general-purpose high level language that was originally developed by Dennis Ritchie for
the Unix operating system. It was first implemented on the Digital Eqquipment Corporation
PDP-11 computer in 1972.
The Unix operating system and virtually all Unix applications are written in the C language. C
has now become a widely used professional language for various reasons.
• Easy to learn
• Structured language
• It produces efficient programs.
• It can handle low-level activities.
• It can be compiled on a variety of computers.
Facts about C
• C was invented to write an operating system called UNIX.
• C is a successor of B language which was introduced around 1970
• The language was formalized in 1988 by the American National Standard Institue
(ANSI).
• By 1973 UNIX OS almost totally written in C.
• Today C is the most widely used System Programming Language.
• Most of the state of the art software have been implemented using C
Why to use C?
C was initially used for system development work, in particular the programs that make-up the
operating system. C was adoped as a system development language because it produces code that
runs nearly as fast as code written in assembly language. Some examples of the use of C might
be:
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
HUMAN COMPUTER EDUCATION MISSION
AN ISO 9001:2015 CERTIFIED INSTITUTION & REGD. GOVT OF INDIA
• Data Bases
• Language Interpreters
• Utilities
C Program File
All the C programs are writen into text files with extension ".c" for example hello.c. You can use
"vi" editor to write your C program into a file.
HISTORY TO C LANGUAGE
C is a general-purpose language which has been closely associated with the UNIX operating
system for which it was developed - since the system and most of the programs that run it are
written in C.
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards.
The influence of BCPL on C proceeded indirectly through the language B, which was written by
Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a DEC PDP-
7. BCPL and B are "type less" languages whereas C provides a variety of data types.
In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C Programming
Language by Kernighan & Ritchie caused a revolution in the computing world.
In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI
C", was completed late 1988.
BASIC STRUCTURE OF C PROGRAMMING
C KEYWORDS
C keywords are the words that convey a special meaning to the c compiler. The keywords
cannot be used as variable names.
The list of C keywords is given below:
volatile while
C CONSTANTS
A C constant refers to the data items that do not change their value during the program
execution. Several types of C constants that are allowed in C are:
Integer Constants
Integer constants are whole numbers without any fractional part. It must have at least one digit
and may contain either + or – sign. A number with no sign is assumed to be positive.
There are three types of integer constants:
Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or + sign.
Example of valid decimal integer constants
341, -341, 0, 8972
Octal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is said
to be octal integer constants.
STRING CONSTANTS
String constants are sequence of characters enclosed within double quotes. For example,
―hello‖
―abc‖
―hello911‖
Every sting constant is automatically terminated with a special character „‟ called thenull
character which represents the end of the string.
For example, ―hello‖ will represent ―hello‖ in the memory.
Thus, the size of the string is the total number of characters plus one for the null character.
VARIABLES
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive. Based on the basic types explained in the previous chapter, there will be the
following basic variable types −
Type Description
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable.
A variable definition specifies a data type and contains a list of one or more variables of that
type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to
create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
4 Logical operators
These operators are used to perform logical
ARITHMETIC OPERATORS IN C
C Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus in C programs.
Arithmetic
S.no Operators Operation Example
1 + Addition A+B
2 – Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
int main()
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
OUTPUT:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
ASSIGNMENT OPERATORS IN C
In C programs, values for the variables are assigned using assignment operators.
For example, if the value ―10‖ is to be assigned for the variable ―sum‖, it can be assigned as
―sum = 10;‖
Simple
assignment 10 is assigned
operator = sum = 10 to variable sum
This is same as
-= sum -= 10 sum = sum – 10
This is same as
/+ sum /= 10 sum = sum / 10
This is same as
sum %= sum = sum %
%= 10 10
This is same as
sum = sum &
&= sum&=10 10
Compound
assignment sum ^= This is same as
operators ^= 10 sum = sum ^ 10
int main()
int Total=0,i;
for(i=0;i<10;i++)
OUTPUT:
Total = 45
RELATIONAL OPERATORS IN C
Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a C program.
x is greater than
1 > x>y y
x is greater than
3 >= x >= y or equal to y
x is less than or
4 <= x <= y equal to y
x is not equal to
6 != x != y y
int main()
int m=40,n=20;
if (m == n)
else
OUTPUT:
It returns true
when both
logical conditions
1 && AND (x>5)&&(y<5) are true
It returns true
when at-least
one of the
logical condition is
2 || OR (x>=10)||(y>=10) true
It reverses the
state of the
operand
―((x>5) &&
(y<5))‖
If ―((x>5)
&& (y<5))‖
is true,
logical NOT
logical operator
3 ! NOT !((x>5)&&(y<5)) makes it false
int main()
int o=20,p=30;
if (o>p || p!=20)
else
OUTPUT:
In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.
HUMAN COMPUTER EDUCATION MISSION
AN ISO 9001:2015 CERTIFIED INSTITUTION & REGD. GOVT OF INDIA
&& operator – ―if clause‖ becomes true only when both conditions (m>n and m! =0) is true.
Else, it becomes false.
|| Operator – ―if clause‖ becomes true when any one of the condition (o>p || p!=20) is true. It
becomes false when none of the condition is true.
! Operator – It is used to reverses the state of the operand.
If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by ―!‖
operator.
So, ―! (m>n and m! =0)‖ returns false (0).
x x
& ^
x y x|y y y Operator_symbol Operator_name
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y= 01010000
Note:
Bit wise NOT: Value of 40 in binary
is0000000000000000000000000000000000000000000000000010100000000000. So, all 0‘s are
converted into 1‘s in bit wise NOT operation.
Bit wise left shift and right shift : In left shift operation ―x << 1 ―, 1 means that the bits will be
left shifted by one place. If we use it as ―x << 2 ―, then, it means that the bits will be left shifted
by 2 places.
int main()
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
OUTPUT:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
int main()
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
OUTPUT:
x value is 1
y value is 2
C – Increment/decrement Operators
PREVNEXT
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator: ++var_name ;( or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
EXAMPLE PROGRAM FOR INCREMENT OPERATORS IN C
In this program, value of ―i‖ is incremented one by one from 1 up to 9 using ―i++‖ operator and
output is displayed as ―1 2 3 4 5 6 7 8 9‖.
//Example for increment operators
#include <stdio.h>
int main()
int i=1;
while(i<10)
printf("%d ",i);
i++;
#include <stdio.h>
int main()
int i=20;
while(i>10)
printf("%d ",i);
i--;
OUTPUT:
20 19 18 17 16 15 14 13 12 11
1 Pre increment
++i Value of i is
Value of i is
incremented after
i++ assigning it to variable
2 Post–increment i.
Value of i is
decremented before
— –i assigning it to variable
3 Pre decrement i.
Value of i is
decremented after
i– — assigning it to variable
4 Post_decrement i.
#include <stdio.h>
int main()
int i=0;
while(++i < 5 )
printf("%d ",i);
return 0;
int main()
int i=0;
while(i++ < 5 )
printf("%d ",i);
return 0;
OUTPUT:
12345
int main()
int i=10;
while(--i > 5 )
printf("%d ",i);
return 0;
OUTPUT:
9876
int main()
int i=10;
while(i-- > 5 )
return 0;
OUTPUT:
98765
SPECIAL OPERATORS IN C:
Below are some of special operators that C language offers.
Example : * a where, * is
2 * pointer to the variable a.
int main()
int *ptr, q;
q = 50;
ptr = &q;
printf("%d", *ptr);
return 0;
OUTPUT:
50
#include <limits.h>
int main()
int a;
char b;
double d;
return 0;
OUTPUT:
EXPRESSIONS
Arithmetic expression in C is a combination of variables, constants and operators written in a
proper syntax. C can easily handle any complex mathematical expressions but these
mathematical expressions have to be written in a proper syntax. Some examples of mathematical
expressions written in proper syntax of C are
Note: C does not have any operator for exponentiation.
C operators in order of precedence (highest to lowest). Their associativity indicates in what order
operators of equal precedence in an expression are applied.
Operator Description Associativity
() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
Note 1:
Parentheses are also used to group sub-expressions to force a different
precedence; such parenthetical expressions can be nested and are
evaluated from inner to outer.
Note 2:
Postfix increment/decrement have high precedence, but the actual
increment or decrement of the operand is delayed (to be accomplished
sometime before the statement completes execution). So in the
statement y = x * z++; the current value of z is used to evaluate the
expression (i.e., z++ evaluates to z) and z only incremented after all else
is done.
In this syntax format is the format specification string. This string contains, for each variable to
be output, a specification beginning with the symbol % followed by a character called the
conversion character.
Example:
printf (―%c‖, data1);
The character specified after % is called a conversion character because it allows one data type to
be converted to another type and printed.
See the following table conversion character and their meanings.
Conversion Meaning
Character
d The data is converted to decimal (integer)
c The data is taken as a character.
s The data is a string and character from the string , are printed until a NULL,
character is reached.
DECISION STATEMENTS
If statement:
Syntax :
if(expression)
statement1;
Explanation :
• Expression is Boolean Expression
• It may have true or false value
Meaning of If Statement :
• It Checks whether the given Expression is Boolean or not !!
• If Expression is True Then it executes the statement otherwise jumps to next_instruction
Sample Program Code :
void main()
{
int a=5,b=6,c;
c=a+b;
printf("Execute me 2");
}
Output :
Execute me 1
If Statement :
if(conditional)
{
Statement No 1
Statement No 2
Statement No 3
.
.
.
Statement No N
}
Note :
More than One Conditions can be Written inside If statement.
1. Opening and Closing Braces are required only when ―Code‖ after if statement
occupies multiple lines.
if(conditional)
Statement No 1
Statement No 2
Statement No 3
In the above example only Statement 1 is a part of if Statement.
1. Code will be executed if condition statement is True.
2. Non-Zero Number Inside if means “TRUE Condition”
if(100)
printf("True Condition");
if-else Statement :
Syntax :
if(expression)
{
statement1;
statement2;
}
else
{
statement1;
statement2;
}
next_statement;
Explanation :
If expression is True then Statement1 and Statement2 are executed
Otherwise Statement3 and Statement4 are executed.
Sample Program on if-else Statement :
void main()
{
int marks=50;
if(marks>=40)
{
printf("Student is Pass");
}
else
{
printf("Student is Fail");
}
}
Output :
Student is Pass
Flowchart : If Else Statement
if(num == 20)
{
printf("True Block");
}
else
{
printf("False Block");
}
If part Executed if Condition Statement is True.
if(num == 20)
{
printf("True Block");
}
True Block will be executed if condition is True.
Else Part executed if Condition Statement is False.
else
{
printf("False Block");
}
Consider Example 2 with Explanation :
if(num == 20)
{
printf("True Block");
}
else
{
printf("False Block");
}
If part Executed if Condition Statement is True.
if(num == 20)
{
printf("True Block");
}
True Block will be executed if condition is True.
Else Part executed if Condition Statement is False.
Switch statement
Why we should use Switch Case?
• One of the classic problem encountered in nested if-else / else-if ladderis
called problem of Confusion.
• It occurs when no matching else is available for if .
• As the number of alternatives increases the Complexity of program increases
drastically.
• To overcome this , C Provide a multi-way decision statement called ‗Switch
Statement‗
See how difficult is this scenario?
if(Condition 1)
Statement 1
else
{
Statement 2
if(condition 2)
{
if(condition 3)
case value2 :
body2
break;
case value3 :
body3
break;
default :
default-body
break;
}
next-statement;
Flow Diagram :
incrementation;
}
Note :
For Single Line of Code – Opening and Closing braces are not needed.
while(1) is used for Infinite Loop
Initialization , Incrementation and Condition steps are on different Line.
While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then and then
only code is executed ]
Do while:
Do-While Loop Syntax :
initialization;
do
{
incrementation;
}while(condition);
if(condition)
{
}
}
If we have block of code that is to be executed multiple times then we can use curly braces to
wrap multiple statement in for loop.
}
this is bodyless for loop. It is used to increment value of ―i‖.This verity of for loop is not used
generally.
At the end of above for loop value of i will be 5.
if(breaking condition)
break;
i++;
}
Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause
overflow of stack.
Form Comment
for ( i=0 ; i < 10;i++) ; For Loop with no Body (Carefully Look at the
Semicolon)
JUMP STATEMENTS:
Break statement
Break Statement Simply Terminate Loop and takes control out of the loop.
Note :
It is used for skipping part of Loop.
Continue causes the remaining code inside a loop block to be skipped and causes execution to
jump to the top of the loop block
for
do-while
Goto statement:
goto label;
label :
Whenever goto keyword encountered then it causes the program to continue on the line , so long
as it is in the scope .
Types of Goto
Forward
Backward
What is an array?
An array is a collection of similar datatype that are used to allocate memory in
a sequential manner.
Syntax : <data type> <array name>[<size of an array>]
Subscript or indexing: A subscript is property of an array that distinguishes all its stored
elements because all the elements in an array having the same name (i.e. the array name). so to
distinguish these, we use subscripting or indexing option.
e.g. int ar[20];
First element will be: int ar[0];
Second element will be: int ar[1];
Third element will be: int ar[2];
Fourth element will be: int ar[3];
Fifth element will be: int ar[4];
Sixth element will be: int ar[5];
So on……………………
Last element will be: int ar[19];
Types of Array
1. Static Array
2. Dynamic Array.
Static Array
An array with fixed size is said to be a static array.
Types of static array:
1. One Dimensional Array
2. Two Dimensional Array.
3. Multi Dimensional Array.
Dynamic Array.
This type of array also does not exist in c and c++.
Example: Program based upon array:
WAP to store marks in 5 subjects for a student. Display marks in 2 nd and 5thsubject.
#include<stdio.h>
#include<conio.h>
void main()
{
int ar[5];
int i;
for(i=0;i<5;i++)
{
printf(― \n Enter marks in ―,i, ―subject‖);
scanf(―%d‖,&ar[i]);
}
printf(―Marks in 2nd subject is: ‖,ar[1]);
printf(―Marks in 5th subject is: ‖,ar[4]);
}
STRINGS
What is String?
· A string is a collection of characters.
· A string is also called as an array of characters.
· A String must access by %s access specifier in c and c++.
· A string is always terminated with \0 (Null) character.
· Example of string: ―Gaurav‖
· A string always recognized in double quotes.
· A string also consider space as a character.
String Functions in C:
Our c language provides us lot of string functions for manipulating the string.
All the string functions are available in string.h header file.
1. strlen().
This string function is basically used for the purpose of computing the ength of string.
2. strupr().
This string function is basically used for the purpose of converting the case sensitiveness of the
string i.e. it converts string case sensitiveness into uppercase.
3. strlwr ().
This string function is basically used for the purpose of converting the case sensitiveness of the
string i.e it converts string case sensitiveness into lowercase.
Example: char str = ―gaurav‖
strlwr(str);
printf(―The Lowercase of the string is :%s ‖,str);
4. strcmp ().
This string function is basically used for the purpose of comparing two string.
This string function compares two strings character by characters.
Thus it gives result in three cases:
Case 1: if first string > than second string then, result will be true.
Example:
char str1= ―Gaurav‖;
char str2= ―Arora‖;
char str3=strcmp(str1,str2);
printf(―%s‖,str3);
5. strcat().
This string function is used for the purpose of concatenating two strings ie.(merging two or more
strings)
Example:
char str1 = ―Gaurav‖;
char str2 = ―Arora‖;
char str3[30];
str3=strcat(str1,str2);
printf(―%s‖,str3);
6. strcpy()
This string function is basically used for the purpose of copying one string into another string.
char str1= ―Gaurav‖;
char str2[20];
str2 = strcpy(str2,str1);
printf(―%s‖,str2);
6. strrev()
This string function is basically used for the purpose of reversing the string.
char str1= ―Gaurav‖;
char str2[20];
# include<stdio.h>
# include<conio.h>
#include<string.h>
void main()
{
char str[20];
char str1[20];
int opt,len;
printf(―\n MAIN MENU‖);
printf(―\n 1. Convert string into upper case‖);
printf(―\n 2. Reverse the string‖);
printf(―\n 3. Copy one string into another string‖);
printf(―\n 4.Compute length of string ‖);
printf(―Enter string ‖);
scanf(―%s‖, &str);
printf(―Enter your choice‖);
scanf(―%d‖,&opt);
switch(opt)
{
case 1: strupr(str);
case 2: strrev(str);
printf(―The reverse of string is : %s‖,str);
break;
case 3: strcpy(str1,str);
printf(―New copied string is : %s‖,str1);
break;
case 4: len=strlen(str);
printf(―The length of the string is : %s‖,len);
break;
default: printf(―Ypu have entered a wrong choice.‖);
}
FUNCTIONS
FUNCTIONS
A function is itself a block of code which can solve simple or complex task/calculations.
A function performs calculations on the data provided to it is called "parameter" or "argument".
A function always returns single value result.
Types of function:
1. Built in functions(Library functions)
a.) Inputting Functions.
b.) Outputting functions.
Parts of a function:
1. Function declaration/Prototype/Syntax.
2. Function Calling.
3. Function Definition.
1.)Function Declaration:
Syntax: <return type > <function name>(<type of argument>)
The declaration of function name, its argument and return type is called function declaration.
Recursion
Firstly, what is nested function?
When a function invokes another function then it is called nested function.
But,
When a function invokes itself then it is called recursion.
NOTE: In recursion, we must include a terminating condition so that it won't execute to infinite
time.
INTRODUCTION TO STRUCTURE
As we know that Array is collection of the elements of same type , but many time we have to
store the elements of the different data types.
Suppose Student record is to be stored, then for storing the record we have to group together all
the information such as Roll, name, Percent which may be of different data types.
Definition of Structure in C
Structure is composition of the different variables of different data types, grouped under same
name.
typedef struct {
char name[64];
char course[128];
int age;
int year;
} student;
char name[64];
char course[128];
int age;
int year;
Structure member may be of different data type including user defined data-type also
typedef struct {
char name[64];
char course[128];
book b1;
int year;
} student;
In C we can group some of the user defined or primitive data types together and form another
compact way of storing complicated information is called as Structure. Let us see how to declare
structure in c programming language –
struct tag
data_type1 member1;
data_type2 member2;
data_type3 member3;
};
struct <structure_name>
structure_Element1;
structure_Element2;
HUMAN COMPUTER EDUCATION MISSION
AN ISO 9001:2015 CERTIFIED INSTITUTION & REGD. GOVT OF INDIA
structure_Element3;
...
...
};
Memory is created, very first time when the variable is created /Instance is created.
struct date
int date;
char month[20];
int year;
}today;
struct date
int date;
char month[20];
};
struct Book
int pages;
char name[20];
int year;
}book1,book2,book3;
C Structure Initialization
Let us discuss very familiar example of structure student , we can initialize structure variable in
different ways –
struct student
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3 };
In the above code snippet, we have seen that structure is declared and as soon as after declaration
we have initialized the structure variable.
HUMAN COMPUTER EDUCATION MISSION
AN ISO 9001:2015 CERTIFIED INSTITUTION & REGD. GOVT OF INDIA
std1 = { "Pritesh",67,78.3 }
struct student
char name[20];
int roll;
float marks;
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
In this example, we have declared two structure variables in above code. After declaration of
variable we have initialized two variable.
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
struct student
int mark1;
int mark2;
int mark3;
} sub1={67};
Though there are three members of structure,only one is initialized , Then remaining two
members are initialized with Zero. If there are variables of other data type then their initial
values will be –
integer 0
float 0.00
char NULL
struct student
int mark1;
int mark2;
int mark3;
};
void main()
- - - - --
- - - - --
- - - - --
};
When we declare a structure then memory won‘t be allocated for the structure. i.e only writing
below declaration statement will never allocate memory
struct student
int mark2;
int mark3;
};
struct
int length;
char *name;
}*ptr;
length = 30;
*name = "programming";
++ptr->length