Cebookppt 170428164431
Cebookppt 170428164431
Cebookppt 170428164431
www.spendwithme.com
Introduction of C Programming
Language
Chapter-1
What is Programming language?
All human beings communicate each other by their own languages. if
computer needs to communicate with other so they designed the
Programming language. It is intermediate between human being and
machine. It is also refer as computer language.
Computer follow the instructions given by the programmer and its
perform the tasks. Programs are set of instructions and that is called
software.
3 levels of programming language
Low level languages
Low level language is a machine code. It does not need any compiler or
interpreter for run. it is used to writing operating systems, firmware and
micro controllers. Directly it can manage the memory.
Examples:
Assembly and machine code
Middle level languages
Middle level language is used to write operating system as
well as application programming. It has virtual machines
to compile and interpreted the languages. Easy to reason
about the program flow. It does not provide all built in
functions available in high level languages.
Examples:
C, C++
High level languages
High level language is easy to read, write and maintain. It
must be translated into machine language/code by using
interpreter or compiler. process of developing a program is
more simpler and understandable.
Examples:
Java , python, perl, ruby
History of C
C is a general purpose structured/procedural language. C was
developed by Dennis ritchie in 1972 at AT&T(American
telephone and telegraph) bell lab. In 1978 brain Kernighan and
Dennis Ritchie was published the first edition of C Programming
Language. So it is known as K&R C.
C Language overcomes the all problems in the B and BCPL(Basic
Combined Programming Language) languages. C has features of B an
BCPL.
C language creates the UNIX operating system, C compiler and UNIX
application programs. It is used to create the system programming
languages and interacts between hardware like drivers and kernel etc.
Linux OS,RDBMS and SQL are written in C Language.
C is base for all other computer languages that’s why it is called as
mother language.
It can be defined in many ways as follows
Mother language
Mid level language
System programming language
Structure oriented language
Procedural language
Features of C
C is widely used in system programming. It has some features.
Portable/Machine independent
Simple
fast
Extensible
Memory Management
Rich library
pointers
Recursion
Uses of C
Initially C was used in system development, specifically
to make the programs for operating systems. Later it will
used in system applications. Here we have examples
that uses the C Languages as below.
Operating systems
Embedded systems
Graphic packages
Spreadsheets
Network drivers
Assemblers
Compiler & interpreter
Databases
Installation of C
There are many compilers available for C. Here we are going to use turbo C++ 3.2
.both C and C++ we can work out it.
First download the turbo C++ software from any other sites as you wish.
If you have previous version in your computer please uninstall it.
Extract the turbo C++ 3.2.zip file.
Run the setup.exe file.
Follow the setup instructions to install the turbo c++.
How to use turbo c++?
Double click turbo C++ icon on your desktop.
Now simply click start turbo c++ button and start writing programs.
Structure of C Program
Global variable
Variable that is declared outside the function or block is called global
variable. We can access these variable in any functions. It must be declared at the
beginning of the block.
Example:
printf() and scanf() function in C
Example:
‘5’,’N’,”program”,”235”…..etc.
Octal & Hexadecimal constants
Octal constants are start with 0.
Hexadecimal constants are starts with 0x.
Example:
078, 093... etc .
0x12, 0x45 .. etc.
Backslash character constants
These are used for output functions. It is also known as Escape sequences.
Rules for creating backslash constants
It must begins with backslash symbol (/).
Two ways using const keyword in C
1. const keyword
2. #define preprocessor
Const keyword
It can be start with const keyword to declare constants.
Syntax:
const VARIABLE_NAME=VALUE;
Note:-it will be better by naming constant in capitals.
Example
Output:
#define Preprocessor
It is used to defining the constants
Syntax:
#define variable_name value;
Example:
Output:
Operators
Operators are symbols that is used to perform some
mathematical/logical operations.
Types of operators
Arithmetic operators
Assignment operators
Relational operators
Logical operators
Bitwise operators
Conditional/Ternary operators
Increment& Decrement operators
Misc/Special operators
Arithmetic operators
These are used to perform mathematical calculations like
addition, subtraction, multiplication, division.
Example:-
Output:
Assignment operators
These are used to assign/initialize the values to the variables.
Example:
A=7;
B+=5 is equal to B=B+5;
c-=10 is equal to c=c-10;
d*=3 is equal to d=d*3;
e/=13 is equal to e=e/13;
f%=28 is equal to f=f%=28;
g<<=4 is equal to g=g<<4;
h>>=78 is equal to h=h>>78;
i&=18 is equal to i=i&18;
j^=25 is equal to j=j^25;
k!=9 is equal to k=k!=9;
Relational operators
These operators are used to compare the value of
two variables.
Note:-here true will be 1 false will be 0.
Example:
Output
Logical operators
These operators are used to perform logical operations between two variables.
Example:
Output
Bitwise operators
These operators are used to perform bitwise operations.
Example
If a=60,b=13
a=0011 1100
B=0000 1101
(a&b)=0000 1100
(a|b)=0011 1101
(a^b)=0011 0001
~a=1100 0011
a<<2=240 i.e 1111 0000
a>>2=15 i.e 0000 1111
Conditional/ternary operator
It return the value when condition is true otherwise it
returns false value.
Syntax:
Condition?true_value:false_value;
Example:
Output
Increment & Decrement operators
These operators are used to increase and decrease the
value of the variables.
Misc/Special operators
Example
Output
Format specifiers/string
Format specifiers will be used with printf() function. It start with (% )
percentage operator.
Types of format specifiers as follows:
Example:
Input and output functions
getchar()-It is use to get a single character.
syntax: variable_name=getchar();
putchar()-It is use to print a single character.
Syntax: putchar(variable_name);
}
else
printf("c is big");
}
else
{
if(b>c)
printf("b is big");
else
printf("c is big");
}
getch();}
Loop control statements
Loop statements are used to execute the program
multiple times until condition becomes true. If it
becomes false then it will come out of the loop.
It saves the code and it is used process the values of
array. It is also known as iteration statements.
Types of looping statements
There are 3 types loops available in C.
I. while
II. do while
III. for
Syntax for while loop
while(condition)
{
Body of the loop;
}
Example
Syntax for do while
do
{
Body of the loop;
}while(condition);
Example
Output
Enter a table value:2
2
4
6
8
10
12
14
16
18
20
Difference between while and do while
Syntax For for loop
for(initialization;condition;increment/decrement)
Example
Infinite for loop
If you don’t have initialization, condition and increment/decrement in
for loop then it is called infinite loop. its condition never becomes false.
If you want to terminate the loop the then press ctrl+c. It is also called
endless loop.
It will the cause the computer freezing. Simply you place the 2
semicolons on the for loop it becomes infinite loop.
Syntax:
for(; ;)
Example
#include<stdio.h>
#include<conio.h>
void main()
{
for(;;)
{
printf("it will run forever...");
}
getch();
}
Switch statement
Switch statement is used to execute the program in multiple conditions. Just
like nested if statement, but only difference is if condition fails it will execute
the default block.
In each case it has break statement to stop running the program and move it on
next case.
Syntax
switch(variable_name)
{
case 1:
statements;
break;
.
.
.
.
case n:
statements;
break;
default:
statements;
break;
}
Note: - It is optional to have default statement in our case and this
statement can be placed in anywhere.
Rules for creating switch statements
◦ Case label must be same.
◦ Case labels must ends with colon(:) .
◦ Case labels must be integer literal or single character literal.
◦ Case labels are not floating point.
◦ One or more cases are share the one break statement.
◦ Relational operators are allowed in switch.
◦ Const variables are allowed in switch.
◦ Empty switch case will be allowed.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char v;
printf("enter v value:");
scanf("%c",&v);
switch(v)
{
case 'a':
printf("Apple");
break;
case 'e':
printf("Elegant");
break;
case 'i':
printf("intelligent");
break;
case 'o':
printf("orange");
break;
case 'u':
printf("unity");
break;
default:
printf("it is not vowel");
break;
}
getch();
}
Nested switch statements
Switch within another switch statement is called nested switch.
Example:
#include <stdio.h>
#include<conio.h>
void main () {
int a = 10;
int b = 23;
switch(a) {
case 10:
printf("This is outer switch\n", a );
switch(b) {
case 23:
printf("This is inner switch\n", a );
}
}
printf("value of a is : %d\n", a );
printf(" value of b is : %d\n", b );
getch();
}
Jumping statements
Jump statements are used to transfer the control of the
program unconditionally.
There are 4 types of jumping statements available in C as
follows.
break
continue
goto
break
break statement is used to terminate the loop immediately
when it is encountered. It used with the decision making
statements(if,else..) and looping statements (while, do while,
for).
Incase of inner loop it will terminate only the inner loop.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
while(i<=10)
{
printf("\n%d",i);
if(i==5)
break;//if it reach the value of the 5 then it will come out of the
loop.
i++;
}
getch();
}
Example for break with inner loop
#include <stdio.h>
#include <conio.h>
void main(){
int i=1,j=1;//initializing a local variable
clrscr();
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
printf("%d &d\n",i,j);
if(i==2 && j==2){
break;//will break loop of j only
}
}
}//end of for loop
getch();
}
Output
11
12
13
21
22
31
32
33
Continue
Continue statement is used to skip the given condition and it
continue the execution of the loop(while,do while,for).
In other words it will do the next iteration.
This statement used within the if condition. In case of the inner loop
it will continue the inner loop only.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=0;i<=10;i++)
{
if(i==5)
continue;//it will skip value of 5 and it will continue the execution
printf("\n%d",i);
}
getch();
}
Example for contine with inner loop
#include <stdio.h>
#include <conio.h>
void main(){
int i=1,j=1;//Assigning a local variable
clrscr();
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
if(i==2 && j==2){
continue;//will continue loop of j only
}
printf("%d &d\n",i,j);
}
}//end of for loop
getch();
}
Output
11
12
13
2 1//here continue statement works out for j(inner loop)only. Doesn’t work outer
loop(i)
23
31
32
33
Goto
goto statement is used to transfer the control of program to
the labeled statement. Goto have labeled statement must
followed by colon (:).
It transfers the control to other parts of the program.
Programmers rarely used this statement because it is less
readable and complex.
Syntax:
goto label_name;
label_name:
Note:
Again and again it will execute the code. Good programmers
will not use this statement.
Difference between break and continue
Volatile keyword in C
Volatile keyword can be used with the variables. When
your variable will be marked as volatile the value of the
variable will be change at any time without explicitly by the
compiler.
For example, if global variable’s address is passed to
clock routine of the operating system to store the system
time, the value in this address keep on changing without
any assignment by the program. These variables are named
as volatile variable.
Syntax:
Datatype volatile variable_name;
[or]
Volatile datatype variable_name;
Example:
int volatile n;
volatile float f;
Type casting in C
Type casting is used to convert one datatype into
another datatype. New datatype will be placed before the
variable_name with in the paratheses ( ). if you want to
store a 'long' value into a simple integer then you can type
cast 'long' to 'int'.
It is best to convert lower data type into higher data
type to avoid data loss. There will be implicit and explicit
conversions available in C.
One use for typecasting for is when you want to use the
ASCII characters. For example, what if you want to create
your own chart of all 128 ASCII characters. To do this, you
will need to use to typecast to allow you to print out the
integer as its character equivalent
Types of casting
There are two types casting available in C as follows.
◦ Implicit casting
◦ Explicit casting
Implicit and Explicit casting
Converting lower datatype into higher type is called implicit
casting. It is also called as upcasting. It does not have any
information loss.
Opposite of implicit casting is called explicit casting..it is also
known as downcasting. downcast results in information loss as
lower data type have lesser bits and can hold the lesser amount of
information/data. One data type considers higher if maximum value
allowed to store in it is greater than the other data type. For
example, float is lower compared to double because double can
store more precisions
Example for implicit casting:
int i=10;
long l= i;//implicit casting/conversion
order of datatypes from highest to lowest given below
long doubledoublefloatunsigned long longlong
longunsigned longlongunsigned intint
Syntax for Explicit casting:
(Type_name)value;
Example for explicit casting
#include<stdio.h>
#include<conio.h>
void main()
{
int a=17,b=5;
double m;
m=(double)a+b;
printf(“result of m:%d\n”,m);
getch();
}
OUTPUT:
Result of m:3.40000000
Note:
Here cast operator will be placed before the division is nothing but ( )
parantheses. It is good to practice using cast operator whenever we need
the conversions.
Predefined type cast functions in C
There are many predefined type cast functions available
in C. These are used to convert one datatype into another.
atof()- converts string into float.
atoi()- converts string into int.
atol()-converts string into long.
For all above functions we have to include header file
#include<stdlib.h>
atof()
It is used to convert string data type into float data type.
Syntax:
atof(variable_name);
Example
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
void main()
{
char a[10] = "32.8";
float f = atof(a);
printf("Value of f = %f\n", f);
getch();
}
atoi()
It is convert string data type into int data type.
Syntax:
atoi(variable_name);
Example
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
void main()
{
char a[10] = "752";
int i = atoi(a);
printf("Value of f = %d\n", i);
getch();
}
atol()
It is convert string data type into long data type.
Syntax:
atol(variable_name);
Example
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
void main()
{
char a[10] = "45611";
long l = atol(a);
printf("Value of l = %ld\n", l);
getch();
}
Array in C
Array is a collection of data elements that holds the fixed number of
values of same type. It is use to store large amount of data. An array is
stored so that position of each element can be evaluated by the index.
Arrays are used to implement the data structure.
If you want to store 50 employee details, for that we allocate 50
variables to the store data, this will more difficult to process the data and
then length of code will be too long. So by using array we can overcome
from that problem. Easily we can access the data by using array.
Whatever size may be define at the declaration of array, we can’t
exceed the limit of size what we declared. Dynamically it doesn’t change
the size.
It can be any of the data types.
Array size must be constant so it has fixed size of data.
Sequenced memory locations are allocated to the store the array values in
the memory.
Array index always starts with 0.
Uses array in C
Less code will be use to access the array data.
Types of Arrays
int a[15];
Initialization of 1d Array
void main( )
{
int x=23;//local variable
void show();
clrscr();
printf(" %d ",x);
show();
getch();
}
void show()
{
printf("\n%d",i);
static
static variables are initialized only once at time of program
creation. It exists at end of the program. It maintains the value
between multiple function calls.
There are two types of static variables available in C.
Local/internal static variables
Global/external static variables
Example:
#include <stdio.h>
#include<conio.h>
static int i=5;//global static variable
void fun() {
static int i=0;//local static variable
int j=0;//local variable
i++;
j++;
printf("i= %d j= %d\n", i, j);
}
void main() {
printf("global static variable value=%d",i);
fun();
fun();
fun();
getch();
}
Output
global static variable value=5
i=1 j=1
i=2 j=1
i=3 j=1
register
register variables allocates the memory in register space. It is used to
access the variables very fast than the other variables.
We can’t get the address of the register variable. It is mostly used in
counter variable.
Register variables also declared as global and local.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
register int i=12;
clrscr();
{
register int i=45;
printf("\n%d",i);
}
printf("\n%d",i);
getch();
}
Pointers in C
Pointer is a variable which holds/points the address of another
variable. It is also called as indicator/ locator that point to an address
of value. It is used to allocate memory dynamically at run time.
It can be any type of data such as int, char, float, long,..etc.
Normal variable stores the value where as pointer stores the
address of the value.
If you do not have any values to assign the pointer then simply
give NULL to the pointer. This is known as null pointer.
The size of pointer is 2 byte.
Operators used in pointers
(&) this is address operator that is used to get the address of
the variable.
(*) this is dereferencing/indirection operator that is used to
get the value of the variable.
(->) this is structure operator that is used to access the
structure elements in pointer.
Uses of pointers in C
Dynamic memory allocation is possible with pointers.
By using pointer we can pass arrays and strings to functions
It reduces the length of the code.
It saves the memory space.
It increases the process speed.
Syntax:
Data_type *variable_name;// * denotes the pointer
variable.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,*p,*q,sum;//*p and *q pointer variables
printf("enter 2 values:");
scanf("%d%d",&a,&b);
p=&a;
printf("Address of p=%u\n",p);
q=&b;
printf("Address of q=%u\n",q);
sum=*p+*q;
printf("sum of 2 no's:%d",sum);
getch();
}
Output
enter 2 values:
5
12
Address of p=65524
Address of q=65522
Sum of 2 no’s:17
Pointer to pointer in C
A pointer stores/points the address another pointer is known pointer to
pointer.
Here pointer p1 indicates the address of pointer p2 and p2 indicates the address
that contains value. By placing ** operator we can use pointer to pointer in C.
Syntax:
Data_type **variable_name;
Example:
#include <stdio.h>
#include<conio.h>
void main () {
int v;
int *ptr;
int **pptr;
v = 30;
/* take the address of v */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of v = %d\n", v );
printf("address of ptr=%u\n",ptr);
printf("Value in *ptr = %d\n", *ptr );
printf("address of pptr=%u\n",pptr);
printf("Value in **pptr = %d\n", **pptr);
getch();
}
Output:
value of v=30
address of ptr=65524
value in ptr=30
address of pptr=65521
value in pprt=30
Pointer using Array
Array is fixed size, where as pointer can store different memory
address. By using pointer we can access the array elements.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int n[]={5,10,15,20,25};
int j;
int *p;
p=n;
//p=&n;//it is illegal to assign the array to pointer using & operator
clrscr();
for(j=-;j<5;j++)
{
printf("\n%d is stored at the address %u",*p,p);
p++;
}
getch();
}
Output:
5 is stored at the address 65516
10 is stored at the address 65518
15 is stored at the address 65520
20 is stored at the address 65522
25 is stored at the address 65524
Array of pointer
We can use the pointer variable as an array, which can
store pointer into any kind of data type. This is known as array
of pointer.
Syntax:
Data_type *variable_name[size];
Example:
#include <stdio.h>
#include<conio.h>
void main () {
int n[] = {2, 4, 6};
int i, *ptr[3];
for ( i = 0; i < 3; i++) {
ptr[i] = &n[i]; /* assign the address of integer. */
}
for ( i = 0; i < 3; i++) {
printf("Value of n[%d] = %d\n", i, *ptr[i] );
}
getch();
}
Output:
Value of n[0]=2;
Value of n[1]=4;
Value of n[2]=6;
Math functions in C
In C we have built in mathematical functions that can be used
to perform mathematical operations. If you want to know use
mathematical functions in your program you have to include
this header file #include<math.h>.
Built in mathematical functions in C
floor( )
sqrt( )
pow( )
round( )
ceil( )
floor( )
It has one argument and it returns the value which is less than
or equal to the argument passed. floor( )Return type is double.
Syntax:
floor(variable_name/argument);
Example:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float f1=6.3,f2=-5.5;
clrscr();
printf("value of f1=%f",floor(f1));
printf("value of f2=%f",floor(f2));
getch();
}
Output:
value of f1=6.00000
value of f2=-6.00000
sqrt()
It is used to return the square root of the passed argument. Return type is
double.
Syntax:
sqrt(variable_name/argument);
Example:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
printf("square root of 18=%f",sqrt(18));
printf("square root of 6=%f",sqrt(6));
getch();
}
output
square root of 18=4.242641
square root of 6=2.449490
pow( )
It is used to find the power of the passed argument. Return type is double.
It has 2 arguments.
Syntax:
pow(base_argument,exponent_argument);
Example
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
printf("2 power 5 is=%f",pow(2,5));
printf("\n6 power 2 is=%f",pow(6,2));
getch();
}
Output
2 power 5 is =32.0000
6 power 2 is=36.0000
round()
It is used to returns the nearest value of the double, long
double and float argument passed. If decimal value .1 to .5
then it returns less than the argument passed. If decimal value
is .6 to .9 then it returns greater than the argument passed.
Syntax
round(variable_name/argument);
Example
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
float i=5.4, j=5.6;
printf("round of %f is %f\n", i, round(i));
printf("round of %f is %f\n", j, round(j));
getch();
}
Output
round of 5.4 is 5.000000
round of 5.6 is 6.000000
ceil( ) getch();
It returns the nearest value which is }
greater than or equal to the passed Output
argument.
ceil value of 12.3=12.000000
Syntax:
ceil value of 16.5=16.000000
ceil(argument/variable_name);
Example:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
printf("ceil value of
12.3=%f",ceil(12.3));
printf("ceil value of
16.5=%f",ceil(16.5));
Character type functions in C
These functions are used for testing and mapping character.
Character functions are defined in include<ctype.h> header file. All
functions has int as parameter and it returns non-zero if condition is
true, otherwise it returns zero.
Pre defined character type functions in C
isalnum( )- It checks whether character is alpha numeric or not. It
returns non-zero if its argument is alphabet/ integer. It returns zero if
its argument is not alphabet/integer.
Syntax:
isalnum(argument/variable_name);
Example:
#include <stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("Enter any character\n");
scanf("%c", &c);
if ( isalnum ( c ) )
printf ( "\nEntered character is alpha numeric" ) ;
else
printf ( "\nEntered character is not alpha numeric" " ) ;
getch();
}
Output
Enter any character
#
Entered character is not alpha numeric
isalpha( )-It checks whether character is alphabetic or not. It returns non-zero
if its argument is lowercase letter/uppercase letter. Otherwise it returns
zero.
Syntax:
isalpha(argument/variable_name);
Example:
#include <stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("Enter any character\n");
scanf("%c", &c);
if ( isalpha ( c ) )
printf ( "\nEntered character is alphabetic" ) ;
else
printf ( "\nEntered character is not alphabetic" ) ;
getch();
}
Output
Enter any character
5
Entered character is not alphabetic
iscntrl( )-It checks whether character is control character or not. It
returns non-zero if its argument is control character. Otherwise it
returns zero.
Note:- control characters are in C \a,\b,\n,\t and \v
Syntax:
iscntrl(argument/variable_name);
Example
#include <stdio.h>
#include<conio.h>
void main()
{
char ch[10] ="helloo\nC";
int i = 0;
clrscr();
while(1)
{
if(iscntrl(ch[i]))
{
printf ( "control character is found at " \
"%dth position\n", i+1);
break;
}
i++;
}
getch();
}
Output
control character is found at 7th position
isdigit( )-It checks whether character is digit or not. It returns
non-zero if its argument is digit. Otherwise it returns zero.
Syntax:
isdigit(argument/variable_name);
Example
#include <stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("Enter any character\n");
scanf("%c", &c);
if ( isdigit ( c ) )
printf ( "\nEntered character is digit" ) ;
else
printf ( "\nEntered character is not digit" ) ;
getch();
}
output
Enter any character 12
Entered character is digit
isgraph( )-It checks whether character is graphical character. It returns
non-zero if its argument is graphical character. Otherwise it returns
zero.
All printable characters are graphical character except ‘ ‘space.
Syntax:
isgraph(argument/variable_name);
Example
#include <stdio.h>
#include<conio.h>
int main()
{
char string[50] ="helloc program";
int i = 0;
clrscr();
while(1)
{
if(isgraph(string[i]))
{
putchar(string[i]);
i++;
}
else break;
}
getch();
}
Output
helloc
islower( )-It checks whether character is lower case or not. It
returns non-zero if its argument is lower case letter.
Otherwise it returns zero.
Syntax:
islower(argument/variable_name);
Example
#include <stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("Enter any character:");
scanf("%c", &c);
if ( islower( c ) )
printf ( "\nEntered character is lower" ) ;
else
printf ( "\nEntered character is not lower" ) ;
getch();
}
Output
Enter any character: n
Entered character is lower
isupper( )- It checks whether character is upper case or not. It
returns non-zero if its argument is upper case letter. Otherwise
it returns zero.
Syntax:
isupper(argument/variable_name);
Example
#include <stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("Enter any character:");
scanf("%c", &c);
if ( isupper( c ) )
printf ( "\nEntered character is upper" ) ;
else
printf ( "\nEntered character is not upper" ) ;
getch();
}
output
Enter any character: A
Entered character is upper
ispunct( )- It checks whether character is punctuation or not. It
returns non-zero if its argument is punctuation. Otherwise it
returns zero.
Syntax:
ispunct(argument/variable_name);
Example
#include <stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("Enter any character:");
scanf("%c", &c);
if ( ispunct( c ) )
printf ( "\nEntered character is punctuation character" ) ;
else
printf ( "\nEntered character is not punctuation character " ) ;
getch();
}
Output
Enter any character: ?
Entered character is punctuation character
isxdigit( )- It checks whether character is Hexadecimal or not. It returns
non-zero if its argument is hexadecimal. Otherwise it returns zero.
Hexadecimal represents 0 to 9 and A to F
Syntax:
isxdigit(argument/variable_name);
#include <stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("Enter any character\n");
scanf("%c", &c);
if ( isxdigit( c ) )
printf ( "\nEntered character is hexadecimal" ) ;
else
printf ( "\nEntered character is not hexadecimal" ) ;
getch();
}
Output
Enter any character: i
Entered character is not hexadecimal
isspace( )- It checks whether character is space or not. It returns non-
zero if its argument is space. Otherwise it returns zero.
Syntax:
isspace(argument/variable_name);
Example
#include <stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("Enter any character\n");
scanf("%c", &c);
if ( isspace( c ) )
printf ( "\nEntered character is space" ) ;
else
printf ( "\nEntered character is not space" ) ;
getch();
}
Output
Enter any character: c
Entered character is not space
Isprint( )- It checks whether character is printable or not. It
returns non-zero if its argument is printable character.
Otherwise it returns zero.
Syntax:
isprint(argument/variable_name);
Example i++;
#include <stdio.h> }
#include<conio.h> else break;
void main() }
{ getch();
char string[50] }
="helloC \n string"; output
int i = 0; helloC
while(1) since it has \n control
{ character after it will
if(isprint(string[i])) not print program.
{
putchar(string[i]);
toupper( )- It is used to change lowercase letter into upper case letter.
Syntax:
toupper(argument/variable_name);
Output
enter 1st string:hello
enter 2nd string:program
size of hello is 5
size of program is 7
program is greater than hello
Example for string reverse
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[15];
clrscr();
printf("enter string to reverse:");
gets(s1);
printf("reverse of given string is=%s",s1);
getch();
}
Output
enter string to reverse:hello
reverse of given string is=olleh
Example for converting convert upper case:");
lower case and upper gets(s2);
case printf("upper case of given
#include<stdio.h> string:%s",strupr(s2));
#include<conio.h> getch();
#include<string.h> }
void main() Output
{ enter string to convert
char s1[10],s2[10]; lower case:HELLO
clrscr(); lower case of given
printf("enter string to string:hello
convert lower case:"); enter string to convert
gets(s1); upper case:program
printf("lower case of given upper case of given
string:%s",strlwr(s1)); string:PROGRAM
printf("enter string to
Structure in C
Structure is a collection of different data type variables are
grouped together under a single name. It is user defined data
type.
Each element/variable declared inside the structure is called
member/ members of structure.
Keyword struct is used to declare the structure in C.
We can declare many variables in same structure. Memory
will be allocated separately.
It is mostly used to store student information, book
information, employee information and patient information, etc.
Uses of structure
Structures are use to store large amount of data. It can be act like
data base.
By using structure we can send data to the printer.
It can be interact with keyboard and mouse to store the data.
It used to check the memory size of the computer.
It is used to clear the output screen contents.
Syntax
struct structure_name
{
Data type variable_name1;
Data type variable_name2;
.
.
.
Data type variable_nameN;
}structure reference_name;
Note: - structure must ends with semicolon (;).
Structure member accessing
. (Dot/member operator for normal variable) it is also called period
operator.
-> (structure pointer operator)
Syntax:
Structure_variable_name.member;
clrscr();
Example:
printf("enter your name:");
#include<stdio.h>
gets(infostr.name);
#include<conio.h>
printf("enter regno:");
struct info
scanf("%d",&infostr.regno);
{
printf("enter your city:");
char name[50];
scanf("%s",&infostr.city);
int regno[20];
printf("Name=%s\nRegno=%
char city[30]; d\ncity=%s\n",infostr.name
}infostr;//infostr is structure ,infostr.regno,infostr.city);
reference name getch();
void main() }
{
//infostr.name=”divya”;// we
can initialize the structure
member like this also
Output
enter your name:nandhini
enter regno:12345
enter your city:Madurai
Name:nandhini
Regno:12345
City:Madurai
Array of structures
It is used to store huge information of different data types. This is also
called collection of structures or structure array.
Example:
#include<stdio.h>
#include<conio.h>
struct book
{
int bid;
char bname[20];
};
void main()
{
struct book b1[5];//here also we can declare structure reference name
int i;
clrscr();
printf("enter 5 books details\n");
for(i=0;i<5;i++)
{
printf("enter book id:");
scanf("%d",&b1[i].bid);
printf("enter book name:");
scanf("%s",&b1[i].bname);
}
printf("\n 5 book details are");
for(i=0;i<5;i++)
{
printf("\nbook id:%d",b1[i].bid);
printf("\nbook name:%s",b1[i].bname);
}
getch();
}
Output book id:33
enter 5 books details book name:cc
enter book id:11 book id:44
enter book name:aa book name:dd
enter book id:22 book id:55
enter book name:bb book name:ee
enter book id:33
enter book name:cc
enter book id:44
enter book name:dd
enter book id:55
enter book name:ee
5 book details are
book id:11
book name:aa
book id:22
book name:bb
passing structure into the functions
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct empinfo
{
int empid;
char ename[15];
}e;
void empdetails(struct empinfo e);//here we passing structure reference into
function
void main()
{
clrscr();
e.empid=452;
strcpy(e.ename,"divya");
empdetails(e);
getch();
}
void empdetails(struct empinfo e)
{
printf("emp id=%d\n",e.empid);
printf("emp name=%s",e.ename);
}
output
empid=452
emp name=divya
Structure using pointers
We can use pointers in structure. By accessing members we use -> operator.
Syntax:
Structure reference_name->member;
Example:
#include<stdio.h>
#include<conio.h>
struct stud
{
int id;
char *name;
char *addr;
};
struct stud s,*stptr;
void main()
{
stptr=&s;
stptr->id=235;
stptr->name="sarjuna";
stptr->addr="kknagar";
printf("student details\n");
printf("id=%d\n name=%s\n address=%s\n",stptr->id,stptr-
>name,stptr->addr);
getch();
}
Output
id=235
name=sarjuna
address=kknagar
Structure with in a structure
One structure declared inside the another structure is called nested
structure. We can access normal variables as well pointer variables.
Syntax
struct out
{
Members of outer structure;
Struct in
{
Members of inner structure;
}inref;
}outref;
Syntax Accessing members in inner structure
outref.inref.members of inner structure;
Example:
#include <stdio.h>
#include <string.h>
#include<conio.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
void main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "indra");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
//printing first employee information
printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n",
e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
getch();
}
Output
employee id : 101
employee name : indra
employee date of joining (dd/mm/yyyy) : 10/11/2014
Unions in C
It is collection of different data type which are grouped together. It is
also like structure. Each element in union is called member.
You can define many members in union, but only one member can
have the value at any given time. Union uses the same memory location to
store the data.
Union holds value for one data type which requires large storage
among their member.
union keyword can be used to declare the union.
Syntax
union union_name
{
Data type variable_name1;
.
.
Data type variable_nameN;
}union_reference_name;
Accessing members of union
Union_reference_name.variable_name1;//for normal variable
Union_reference_name->variable_name1;//pointer variable
Example printf("id=%d",tr.id);
#include<stdio.h> printf("name=%s",tr.name);
#include<conio.h> getch();
union tech }
{
int id;
char name[15];
}tr;
void main()
{
printf("enter developer id:");
scanf("%d",&tr.id);
printf("enter developer name:");
scanf("%s",&tr.name);
printf("developer details are\n");
Output
enter developer id:555
enter developer name:manoj
developer details are
id=555
name=manoj
Difference between structure and union
Memory allocations in C
There are 2 types memory allocation available in C.
1. Static memory allocation
2. Dynamic memory allocation
Static memory allocation
It is used to allocate the memory at compile time. Size is fixed
when program is created. We can change the memory size while run
time. It is used to implement the data segments.
It can be allocate the memory faster than the dynamic
allocation. More memory space is required.
Dynamic memory allocation
It is used to allocate the memory at runtime. It can used to
release the unwanted memory space during the program execution.
It is used to modify the size of the previously allotted memory
space.It allots memory space to array of elements and initialized to
them 0.
Less memory space is required. Slower than the static
allocation.
Dynamic memory allocation functions
It has 4 functions of stdlib.h header file as follows.
1. malloc( )
2. calloc( )
3. realloc( )
4. free( )
malloc()
The malloc( ) is used for memory allocation. It allocated memory of
specified size of the bytes.
It doesn’t not initialize memory at compile time. So by default it has
garbage value.
It returns the null pointer if it doesn’t have specified amount of memory.
Syntax
ptr_variable=(type cast*)malloc(number*sizeof(bytes));
free( )
It is used to releasing the memory allocated by the malloc( ) , calloc( ) and
realloc( ) functions. It returns the memory to the system.
Syntax:
free(variable_name);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int *i;
clrscr();
i=(int*)malloc(5*sizeof(int));//memory allocation
printf("enter i value:");
scanf("%d",i);
printf("value of i=%d",*i);
free(i);//releasing memory
getch();
}
Output
enter i value:12
value of i=12
calloc( )
calloc( ) used for contiguous allocation.It allocates multiple of
blocks specified memory.
It initializes the allocate memory to 0.
It returns NULL if memory is not enough.
Syntax:
Ptr_variable=(cast type)*calloc(n,sizeof(bytes));
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *s;
s=(char*)calloc(10,10*sizeof(char));//memory allocation
clrscr();
strcpy(s,"program");
printf("s=%s",s);
free(s);//releasing memory
getch();
}
Output
s=program
realloc( )
It is used to modify the size of allocated memory. If memory is not enough
for malloc( ) and calloc( ), then use the realloc( ) function for the change
memory size.
Syntax:
ptr_variable=realloc(ptr_variable,new size);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char *pt;
pt=(char*)malloc(6);//memory allocation
clrscr();
strcpy(pt,"MADRAS");
printf("memory contains:%s\n",pt);
pt=(char*)realloc(pt,7);//memory reallocation
strcpy(pt,"CHENNAI");
printf("memory now contains:%s",pt);
free(pt);//releasing memory
getch();
}
Output
memory contains:MADRAS
memory now contains:CHENNAI
Difference between malloc( ) and calloc( )
File Handling in C
File
It is a place on the disk where the related data’s are stored. It
represents the collection of bytes. It can be text file or binary file.It is used
to read, write, and search/close file operations in C.
Normally we use array to store the data but it will lost the data after
program exit. But in file it will not lost the data after program exit. Arrays
are not store the data permanently. Whereas files are stored permanently.
Types of files
There are 2 types of files are as follows.
Text file/System oriented file
Binary file/Stream oriented file
Text file
Text files are normal .txt file than we can easily create using notepad
or some text editors. It contains ASCII codes of digits, alphabetic and
symbols.
We can see all the contents within the file as plain text. we can easily
edit and delete the contents. It takes more storage space.
It is also called as system oriented file.
Binary file
Binary files are .bin files in our computer. It contains the collection bytes (0’s
and 1’s). Binary files are compiled version of text files. It can take large
amount of data. We cannot easily read these files.
More secure than the text files. It is also called as stream oriented file.
File operations
Opening/creating a file- It define how to open a file
Reading a file - It define the process of how to read a file
Writing a file- It define the process of how to write a file
Appending a file- It define the process of how to append a file
Closing a file- It define how to close a file
Modes of file
‘r’- read mode
‘w’-write mode
‘a’- append mode
Functions in file handling
fopen( )- It is used to create/open a file.
fclose( )- It is used to close a file.
fprintf( )- It is used to read a data from file.
fscanf( )- It is used to write a data into a file.
fputc( )- It is used to read character from file.
fgetc( )-It is used to write character into a file.
fgets( )-It is used to read string from file.
fputs( )- It is used to write string into a file.
getw( )- It is used to read integer from file on input stream.
putw( )- It is used to write integer into a file on output stream.
fseek( )- It is use to set the file pointer to the given position.
ftell( )- It is use to returns the current position
rewind( )- It is use to set the file pointer at starting of the file.
Naming a File
Filename.extension
Example:
Empinfo.txt
Opening a file
Syntax
FILE *file_name;
file_name=fopen(“filename.extension”,”mode”);
Note:- FILE must be upper case.
Closing a file
Syntax
fclose(fptr_variable);
fclose(fp);
Syntax for fprintf( ) and fscanf( )
fprintf(file_ptr_variable,”text”,variable_name);
fscanf(file_ptr_variable,”format_specifier”,buffer);
buffer- It is use to get the data.
Format specifier-it can be anything %s,%c,%d,…etc.
Example for writing a file using fprinf( ) and fscanf( )
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
char ar[50];
float percent;
fptr = fopen("stud.txt", "w");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
getch();
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the percentage\n");
scanf("%f", &percent);
fprintf(fptr, "Percentage= %f\n", percent);
printf("file written successfully...\n");
printf("file content is \n");
fclose(fptr);
fopen("stud.txt","r");//open for reading a file
while(fscanf(fptr,"%s",ar)!=EOF)
{
printf("%s",ar);
}
fclose(fptr);
getch();
}
Output
Enter the id
123
Enter the name
Indra
Enter the percentage
98.9
File written successfully..
File content is
123
Indra
98.9
Now you can open current file name stud.txt and then see the content of file.
It will be in /tc directory.
Syntax fputc( ) and fgetc( )
fputc( “character”,file_ptr_variable_name);
character_variable=fgetc(file_ptr_variable_name);
Example for copying a file using fgetc( ) and fputc( )
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fs,*ft;
char s[25],t[25],ch;
clrscr();
printf("enter source file name:");
scanf("%s",&s);
fs=fopen(s,"r");
if(fs=NULL)
{
printf("\n file doesn't exist");
getch();
}
printf("enter target file name:");
scanf("%s",&t);
ft=fopen(t,"w"); Example for Integer I/O file
while((ch=fgetc(fs))!=EOF)// reading using fgetw( ) and fputw( )
a file #include<stdio.h>
fputc(ch,ft);//writing a file #include<conio.h>
fclose(fs);
void main()
fclose(ft);
{
printf("file copied successfully...");
FILE *fp;
getch();
int i,n,a;
}
clrscr();
Output
fp=fopen("io.txt","w");
file copied successfully..
printf("enter any no:");
Now you can see target file name it
scanf("%d",&n);
has the content of source file.
Syntax for fgetw( ) and fputw( ) putw(n,fp);//writing a integer into a
file
fgetw(file_ptr_variable_name);
fclose(fp);
fputw(number,
file_ptr_variable_name);
fp=fopen("io.txt","r"); fclose(fp);
if(fp==NULL) getch();
{ }
printf("file doesn't exist"); Output
getch(); enter any no:45
} number is 45
printf("number is");
while((a=getw(fp))!=EOF)//reading a
integer from file
printf("%d\n",a);
fclose(fp);
getch();
}
printf("number is");
while((a=getw(fp))!=EOF)//reading a
integer from file
printf("%d\n",a);
fseek( )
It is used to write data into file at specified location. It has 3 constants.
SEEK_CUR,SEEK_SET and SEEK_END.
Syntax for fseek( ) and ftell( )
fseek(file_ptr_variable,position,constant);
ftell(file_ptr_variable);
Syntax for fseek( ) and ftell( )
fseek(file_ptr_variable,position,constant);
ftell(file_ptr_variable);
Example:
#include <stdio.h>
#include<conio.h>
void main(){
FILE *fp;
int l;
clrscr();
fp = fopen("f1.txt","w");
fputs("This is program", fp);
fseek( fp, 7, SEEK_CUR);
printf(“file moved…”);
fputs("sample", fp);
fseek( fp, 7, SEEK_CUR);
printf(“file moved…”);
fputs("sample", fp);
l=ftell(fp);
printf(“\nsize of file:%d”,l);
fclose(fp);
}
Output
file moved…
This is program sample
size of file:28
rewind( ) rewind(fp);//moves the file pointer at
It is used to set the file pointer at beginning of the file
the beginning of the stream. while((c=fgetc(fp))!=EOF){
Syntax: printf("%c",c);
rewind(file_ptr_variable); }
Example: fclose(fp);
#include<stdio.h> getch();
#include<conio.h> }
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("f1.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
Output
This is program sample
This is program sample
Here this is program sample printed 2 time, because file pointer points at
beginning that’s why it will printed like this.
Preprocessor directives in C
Preprocessor is a text alternate tool and it instructs the
compiler to do specified pre-processing before the
compilation.
In other words, it is micro processor that is used by the
compiler to transfer your code before compilation. It is known
as micro preprocessor because it can be add macros.
All preprocessor commands must start with hash
symbol(#).
Here we list out the preprocessors available in C as follows.
Macros in C
It is a part of code which is replaced by the value of macro that can be
defined by #define directive.
There are 2 types of macros available in c as follows.
Object like macros.
Function like macros.
Object like macros
It is an identifier replaced by the value than can be used to indicate the
numeric constant.
Example
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define p printf
#define s scanf
void main()
{
int r;
float c;
clrscr();
p("enter r value");
s("%d",&r);
c=2*pi*r;
p("area of circle is=%f",c);
getch();
}
Output
enter r value
6
area of circle=37.68
Function like Macros
We can have function call to define macros.
Example
#include<stdio.h>
#include<conio.h>
#define min(a,b) (a*b)
void main()
{
clrscr();
printf("mul value of a*b=%d",min(12,10));
getch();
}
output
mul value of a*b=120
#undef
It is used to undefined the value.
Syntax:
#undef macro_name
Example for #undef
#include<stdio.h>
#include<conio.h>
#define id 123
/*int i=id;//if we give then it will display
id value because we assign before #undef*/
#undef id
void main()
{
printf("id=%d",id);// it shows error like id is undefined symbol
getch();
}
#ifdef
It is used to give the condition defined by #define preprocessor
Syntax
#ifdef macro_name
Example for #ifdef, #else and #endif
#include<stdio.h>
#include<conio.h>
#define noval
void main()
{
int n;
clrscr();
#ifdef noval
n=2;
#else
printf("enter n value:");
scanf("%d",&n);
#endif
printf("valu of n:%d",n);
getch();
}
Output
value of n:2
#ifndef
It is used to undefine the defined preprocessor directive.
Syntax:
#ifndef macro_name
Example
#include<stdio.h>
#include<conio.h>
#define noval
void main()
{
int n;
clrscr();
#ifndef noval
n=2;
#else
printf("enter n value:");
scanf("%d",&n);
#endif
printf("value of n:%d",n);
getch();
}
Output
Enter n value:12
Value of n:12
Example for #if, #else and #endif
#include<stdio.h>
#include<conio.h>
#define n -2
void main()
{
clrscr();
#if(n<0)
printf("n is negative..");
#else
printf("n is positive");
#endif
printf("\nvalue of n=%d",n);
getch();
}
Output
n is negative..
value of n=-2
#error
It is used to display the error message.
Syntax
#error error_message
Example
#include<stdio.h>
#include<conio.h>
#error include string header file
void main()
{
char s[]="hello";
clrscr();
printf("uppercase of s=%s",strupr(s));
getch();
}
Output
It shows the error include string header file
#pragama
It is used to call function before and after the main function. It provides
additional information to the compiler. It can be used by the operating
system to offer machine or operating system features.
Syntax
#pragama startup function_name
#pragama exit function_name
Note: - startup and exit are predefine #pragama macros.
Example
#include<stdio.h>
#include<conio.h>
void f1();//function declaration
#pragma startup f1
#pragma exit f1
void main()
{
clrscr();
printf("calling main function..");
getch();
}
void f1()
{
clrscr();
printf("calling f1 function..");
getch();
}
Output
calling f1 function
calling main function
calling f1 function