C Programming Notes PDF
C Programming Notes PDF
DISCLAIMER
The data in the tutorials is supposed to be one for reference.
We have made sure that maximum errors have been
rectified. Inspite of that, we (ECTI and the authors) take no
responsibility in any errors in the data.
The programs given in the tutorials have been prepared on,
and for the IDE Microsoft Visual Studio 2013.
To use the programs on any other IDE, some changes might
be required.
The student must take note of that.
www.ecti.co.in
C Programming
History of C Programming
C Programming Language was introduced by Mr. Dennis
Ritchie in 1972. He invented this language for the internal use
of AT & T Bell Labs. But due to the features of C Programming
Language it became very popular.
Problems with languages existing before C –
They were categorized in Lower Level Languages and Higher Level
Languages. The Lower Level Languages were designed to give better
machine efficiency, i.e. faster program execution. The Higher Level
Languages were designed to give better programming efficiency i.e.
faster program development.
The languages before C were Application Specific e.g. FORTRAN
(FORmula TRANslation) was built for Engineering Applications
Development, COBOL (COmmon Business Oriented Language) was
developed for Commercial Application Development.
www.ecti.co.in
C Programming
History of C Programming
Dennis Ritchie thought about giving features of both Lower
Level Languages and Higher Level Languages. So he
introduced the concept of Compilers in C. The function of
compiler is to "Convert the code from Human Readable
Language to Machine Readable Language and Vice-a-Versa".
www.ecti.co.in
C Programming
Basics of C Programming
Alphabets Constants
Numbers Variables Instructions C Program
Special Symbols Keywords
www.ecti.co.in
C Programming
Basics of C Programming
'C' Alphabets:
A, B, ……, Y, Z
Alphabets
a, b, ……..., y, z
Numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols ~ ' @ # % ^ & ( ) _ - + | \ { } [ ] : ; " ' <
> , . ? /
www.ecti.co.in
C Programming
Basics of C Programming
'C' Constants:
A constant is an entity that never changes. There are two type of C
Constants – Primary Constants, Secondary Constants.
C Constants
Primary Secondary
Constants Constants
Array
Integer
Pointer
Real
Structure
Character
etc.
www.ecti.co.in
C Programming
Basics of C Programming
Rules for Constructing Integer Constants:
An Integer Constant must have at least one digit.
It must not have a decimal point.
It can be either positive or negative.
If no sign precedes an Integer Constant, it is assumed to be positive.
No commas or blanks are allowed in integer constant.
The allowable range is: -2,14,74,83,648 to 2,14,74,83,647.
Rules for Constructing Real Constants:
A Real Constant must have at least one digit.
It must have at least one decimal point.
It can be either positive or negative.
Default sign is positive.
No commas or blanks are allowed within Real Constants.
It's range is: 3.4e-38 to 3.4e38.
www.ecti.co.in
C Programming
Basics of C Programming
Rules for Constructing Character Constants:
A character constant is a single alphabet, a single digit or a
single special symbol enclosed within single inverted
commas. Both the inverted commas should point to the
left.
'C' Variables:
An entity that may vary during the program execution is
called as Variable.
Variable names are names given to the memory locations.
These locations can hold integer, real or character constants.
The integer variable needs 4 bytes, float variable needs
4 bytes, double variable needs 8 bytes and char variable
needs 1 byte memory space.
www.ecti.co.in
C Programming
Basics of C Programming
Rules for Constructing a Variable Name:
The variable name should not exceed 30 characters. Some
compilers allow variable names upto 247 characters. But
restrict variable name, as it adds to the typing effort.
The variable name can be Alpha-numeric e.g. no1
But it should start with an alphabet.
It should not contain any spaces in between.
It should not contain any special symbols except
underscore (_) in between e.g. area_circle
It should not contain any Keyword.
www.ecti.co.in
C Programming
Basics of C Programming
Keywords:
The words which are assigned with special meaning to them
in C Compiler are called as keywords. As they are assigned
with special meaning, they can not be used as variable names.
There are only 32 keywords available in C.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
www.ecti.co.in
C Programming
Basics of C Programming
'C' Instructions:
Type Declaration Instruction: These instructions are used to
declare the type of variables used in a C Program.
int no1, no2, sum;
float radius, area;
char ch;
Arithmetic Instructions:
Arithmetic Operators – In normal maths, we write instruction as
Addition + 5+2=7 follows –
Subtraction - 5–2=3 A+B=C
Multiplication * 5 * 2 = 10 In C, we write the same as –
Division / 5/2=2 C=A+B
In C '=' is used to assign values to
Modulus % 5%2=1
variables.
www.ecti.co.in
C Programming
Basics of C Programming
Priority of operators –
Priority Operators Description
1st () Brackets
2nd * / % Multiplication, Division, Modulus
3rd + - Addition, Subtraction
4th = Assignment
www.ecti.co.in
C Programming
Basics of C Programming
Basic Structure of a C Program:
#include<stdio.h> • # – preprocessor
#include<conio.h> instruction
• include<x> – To include a
void main() file x to the C Program
{
……….; • stdio.h / conio.h – Header
……….; Files
……….;
} • void main() – Start of a
program
• { } – Scope of a Program
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
First C Program
#include<stdio.h>
void main()
{
printf("This is my first C Program"); /*to print the statement*/
}
www.ecti.co.in
C Programming
scanf() Function
To receive the values from user scanf() function is used.
You can receive the single or multiple values within a single scanf.
e.g. scanf("%d", &no1) or scanf("%d%d“, &no1, &no2);
Generally before any scanf() statement printf() statement should
be written to guide the user for giving input.
& means address of the variable.
#include<stdio.h>
void main()
{
int no1;
printf(“\nEnter any number: ");
scanf("%d", &no1); /*receives the value from console*/
}
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
Logical Operators
• C contains Logical • if(cond1 && cond2 && …… && condN)
{
Operators && (AND), || ……..;
(OR) and ! (NOT). ……..;
}
• && and || allow to join If all the conditions joined by && are true
then the statements will be executed.
multiple conditions. • if(cond1 || cond2 || …… || condN)
• ! Operator reverses the {
……..;
result of the expression it ……..;
operates on. }
If any of the conditions joined by || is true
Examples - then the statements will be executed.
• if(!flag) /*will reverse value of flag*/ • if((cond1 && cond2) || (cond3 && cond4))
{ {
……..; ……..;
……..; ……..;
} }
www.ecti.co.in
C Programming
In the above example even if the first In the above example if the fist 'if' goes
number is maximum the other two if false then only second if will get
statements are also checked and this executed and if the second 'if' goes
will increase the execution time of the false then the last else will get
program. executed.
www.ecti.co.in
C Programming
int big a, b, c;
big=(a>b ? (a>c ? 3 : 4) : (b>c ? 6 : 8))
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
More Operators
int i = 10, j;
++ and -- operators:
j = ++i;
• When you want to do increment
by one i.e. if you want to write printf(" %d %d", i, j); /* 11 11*/
i = i + 1, you can use i++ or ++i;
Same way if you want to do In the first example the value of i is
decrement by on i.e. if you want to first assigned to j and then the
write i = i – 1, you can use i-- value of i gets incremented.
or --i. In the second example the value of i
• There is a difference between pre- is first incremented and then it is
increment / post-increment or pre- assigned to j.
decrement / post-decrement
Compound Assignment Operators
operators. e.g.
int i = 10, j;
j = i++; i=i+5 i+=5 i=i–5 i-=5
printf(" %d %d", i, j); /* 11 10*/ i=i*5 i*=5 i=i/5 i/=5
i=i%5 i%=5
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
do while Loop
• The difference between while and #include<stdio.h>
do while is the do while loop at #include<conio.h>
least gets executed single time. void main()
initialize the loop counter; {
int no1, no2, sum;
do
char ch;
{
do
...........; {
………; printf("Enter 2 nos: ");
increment / decrement loop scanf("%d%d", &no1, &no2);
counter; sum = no1 + no2;
} while (condition); printf("Sum = %d", sum);
printf("Want to continue <y/n>: ");
• do while loop is generally used flushall();
with odd loops. When the scanf("%c", &ch);
programmer does not know how } while(ch == 'y');
many time the loop will get }
executed the odd loops are used.
www.ecti.co.in
C Programming
for Loop
• for loop specify three things • In for loop the initializations are
about the loop in a single line. done only at the first time.
• The general form of for Then condition is checked and
statement is as follows – while going outside the loop
the loop counter is
for(initialize; condition; increment /
incremented or decremented.
decrement) • You can do multiple
{ initializations or multiple
………..; increments / decrements using
………..; comma separation.
} e.g.
e.g. for(i = 0, j = 5; i < j; i++, j--)
for(i = 0; i <= 10; i++) {
{ printf("%d %d", i, j);
printf("%d", i); }
}
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
Functions
• Sometimes there is a code which #include<stdio.h>
occurs repeatedly inside main. To void pune();
avoid this repetition we write void mumbai();
void main()
functions. Functions helps to
{
reduce length of code.
printf("\nI am in main");
• A function is a block of code that pune(); Call to a
performs a specific assigned task. mumbai(); function
• You can call one function from printf("\nI am back in main");
another function but you cannot getch();
write one function's definition into }
another. void pune()
{
• The scope of the variables is printf("\nI am in Pune");
Function
limited to the function. Definitions
}
• Two different functions can have void mumbai()
variables with same name. But {
their memory locations are printf("\nI am in Mumbai");
different. }
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
Recursive Functions
• You can give a call to a function
from the same function it is called int factorial (int no)
as recursive function. {
int f;
#include<stdio.h>
if( no == 1)
#include<conio.h>
return(1);
int factorial(int );
else
void main()
f = no * factorial (no – 1);
{
return(f);
int no, fact;
}
printf("\nEnter any number: ");
scanf("%d", &no);
• Make sure that the recursive
fact = factorial(no); call is conditional. An
printf("\nThe factorial is: %d", unconditional recursive call will
fact); result to a infinite call.
getch();
}
www.ecti.co.in
C Programming
Recursive Function
from main()
to main()
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
C Preprocessor
• There are several steps involved • The preprocessor directives begin
from the stage of writing a C with # symbol. Generally they are
Program to the stage of getting it placed at the start of the program,
executed. The combination of before function definitions.
these steps is known as the 'Build • Following are the preprocessor
Process'. directives –
• Before the C Program is compiled – Macro Expansion
it is passed through another • Simple Macros
program called as 'Preprocessor'. • Macros with Arguments
• C program is often known as – File Inclusion
'Source Code'. The Preprocessor – Conditional Compilation
works on Source Code and creates – Miscellaneous Directives
'Expanded Source Code'. If
source file is Prog01.C, the
expanded source code is stored in
file Prog01.I. The expanded source
code is sent for compilation.
www.ecti.co.in
C Programming
C Preprocessor
Macro Expansion Some examples -
#define PI 3.142 • #define AND &&
• The above expression is called as We can use AND instead of &&
'macro definition'. During the • #define OR ||
preprocessing PI will be replaced We can use OR instead of ||
with 3.142.
• #define RANGE ( a > 25 && a < 50)
• PI in above example is called as
We can use RANGE instead of
'macro template' and 3.142 is
(a>25 && a < 50)
called as 'macro expansion'.
• #define FOUND printf("Location
• When we compile the program,
Found");
before the source code passes to
the compiler, it is examined by C We can use FOUND instead of
preprocessor for macro printf("Location Found")
definitions. And when it finds the
macro templates they replace it
with appropriate macro expansion.
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
File Inclusion
• This preprocessor directive • You can include these files into
allows us to include one file into main using #include
other. statement.
• The large programs can be – #include "filename"
divided into different files, each – #include<filename>
containing a set of functions.
• #include "filename" will
These files can be included at
search filename into current
the beginning of main program
file. directory as well as specified
list of directories mentioned in
• The files to be included should
the include search path.
have .h extension. This
extension stands for a 'header • #include <filename> will
file'. search the filename into
• Each header file generally specified list of directories
contains related set of functions. only.
– e.g. math.h will contain all functions
related to mathematics.
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
Arrays
• Array is a collection of variables of • You can initialize the array only at
same data type. the time of declaration.
• E.g. if we want to store roll • Array index always starts from
numbers of 100 students, then zero.
you have to define 100 variables • If you want to refer array elements
and which is very difficult to you can use arr[0], arr[1], arr[2]
manage. Instead you can define etc.
one array which can hold 100 • In the following array 10 is a value
variables. at array index 0 having address
• Declare Array: 6231.
int arr[5]; • Memory Map of Array:
int arr[5] = {10,20,30,40,50};
0 1 2 3 4
int arr[ ] = {10,20,30,40,50};
• When you declare an array a arr 10 20 30 40 50
consecutive memory allocation is
done for 5 integers. 6231 6235 6239 6243 6247
www.ecti.co.in
C Programming
Arrays
Accept and Print Array: • As array holds multiple
locations you have to use for
#include<stdio.h> loop while accepting and
#include<conio.h> printing the array.
void main() • You can define an array of
{ bigger size and accept the
int arr[5], i; required no. of values from
printf("\nEnter five numbers: "); user. e.g. you can define an
for(i = 0; i < 5; i++) array of arr[100] and use only
scanf("%d", &arr[i]); 10 locations.
printf("\nYou have entered: ");
for(i = 0; i < 5; i++) • In C Language the bounds
printf(" %d", arr[i]); checking for array is not done.
getch(); So the programmer has to be
} very careful while accepting or
printing the values from array.
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
display(arr, 3, 3);
getch();
}
www.ecti.co.in
C Programming
Strings
• String is a collection of character #include<stdio.h>
variables. Sometimes you need to #include<conio.h>
store name, address where you
have to store more than one void main()
characters, you need strings.
{
• Declare String:
char name[50];
char s[50]; int i;
char s[ ] = {'P','a','r','a','g','\0'}; printf("\nEnter your name: ");
char s[ ] = "Parag"; //scanf("%s", name);
• Memory Map of a String: gets(name);
0 1 2 3 4 5 printf("\nYour name is: %s", name);
printf("\nYour name is: ");
s P a r a g \0
for(i = 0; name[i] != '\0'; i++)
6231 6232 6233 6234 6235 6236 printf("%c", name[i]);
• '\0' character is automatically getch();
appended at the end while }
accepting the string.
www.ecti.co.in
C Programming
Strings
• %s is special format specifier to Standard Library Functions
accept the strings. But it cannot
accept string with spaces. So use Function Use
gets(string-name) function to Finds the length of the
accept string. strlen
string
• You can print the string using
Converts string to
puts(string-name) function. strlwr
lowercase
• You are not needed to accept the
Converts string to
size of strings as you require in strupr
uppercase
case of arrays because C
automatically appends the '\0' Copies string to another
strcpy
character at the end of the string. string
Hence you know when a '\0' Appends one string at
character appears, that is the end strcat
the end of another string
of the string.
strcmp Compares two string
strrev Reverses the string
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
Pointers
printf("\nAddress of i = %u", j);
• Pointer is a variable which can printf("\nAddress of j = %u", &j);
store address of another printf("\nValue of j = %u", j);
variable. printf("\nValue of i = %d", i);
– & means address printf("\nValue of i = %d", *(&i));
printf("\nValue of i = %d", *j);
– * means value at that getch();
address (except declaration) }
• The output of above program:
i Variable name j
Address of i = Value of i =
10 Variable value 6231 6231 10
6231 Variable address 5785 Address of i= 6231 Value of i =
10
#include<stdio.h> Address of j = Value of i =
void main() 6233 10
{ Value of j = 6231
int i = 10, *j;
j = &i;
printf("\nAddress of i = %u", &i);
www.ecti.co.in
C Programming
Pointers
#include<stdio.h> i j k
void main() 10 6231 5827
{
int i = 10, *j, **k;
6231 5827 8989
j = &i;
k = &j; The output of the program:
printf("\nAddress of i = %u", &i); Address of i = 6231
printf("\nAddress of i = %u", j); Address of i = 6231
printf("\nAddress of i = %u", *k); Address of i = 6231
printf("\nAddress of j = %u", &j);
Address of j = 6233
printf("\nAddress of j = %u", k);
Address of j = 6233
printf("\nAddress of k = %u", &k);
printf("\nValue of j = %u", j); Address of k =6235
printf("\nValue of k = %u, k); Value of j = 6231
printf("\nValue of i = %d", i); Value of k = 6233
printf("\nValue of i = %d", *(&i)); Value of i = 10
printf("\nValue of i = %d", *j); Value of i = 10
printf("\nValue of i = %d", **k); Value of i = 10
getch(); Value of i = 10
}
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
Structures
• If we see real world data it is a struct stud
combination of integers, {
characters, floats, arrays, int roll_no;
strings etc. So we can call it as
a heterogeneous data. char name[20];
• If we want to store data of a char gender;
student then we need to store };
her/ his Roll Number, Name, • Above syntax is used to define
Address, Age, Gender, Phone a structure.
No., E-mail etc. So to store this • Memory Map of Structure:
kind of data we can use
structures. roll_no name gender
• Structure is also called as stud 1 Parag Patki 50
User Defined Datatype.
6231 6235 6255
www.ecti.co.in
C Programming
Structures
#include<stdio.h> printf("\nEnter address: ");
#include<conio.h> flushall();
gets(s.address);
struct stud printf("\nEnter gender <y/n>: ");
{ flushall( );
int roll_no; scanf("%c", &s.gender);
char name[50], address[100]; printf("\nRoll No. is: %d", s.roll_no);
char gender; printf("\nName is: %s", s.name);
}; printf("\nAddress is: %s", s.address);
printf("\nGender is: %c", s.gender);
void main() getch();
{ }
struct stud s;
printf("\nEnter roll number:");
scanf("%d", &s.roll_no);
printf("\nEnter name: ");
flushall( );
gets(s.name);
www.ecti.co.in
C Programming
Nested Structures
#include<stdio.h> scanf("%d", &e.p.roll_no);
#include<conio.h> printf("\nEnter Name: ");
flushall( );
struct p_details gets(e.p.name);
{ printf("\nEnter Gender <y/n>: ");
int roll_no; flushall( );
char name[50]; scanf("%c", &e.p.gender);
char gender; printf("\nEnter E-mail: ");
char email[50];
flushall( );
};
gets(e.p.email);
struct e_student
printf("Enter marks of three subjects:");
{
scanf("%d%d", &e.m1, &e.m2);
int m1, m2;
printf("\nName = %s", e.p.name);
struct p_details p;
}; printf("\nRoll No. = %d", e.p.roll_no);
void main() printf("\nGender = %c", e.p.gender);
{ printf("\nEmail = %s", e.p.email);
struct e_student e; printf("Marks = %d %d", e.m1, 2.m2);
printf("\nEnter roll number:"); getch( );
}
www.ecti.co.in
C Programming
Array of Structures
#include<stdio.h> for(i=0; i<size; i++)
#include<conio.h> {
printf("\nEnter roll no.:");
struct student scanf("%d", &s[i].roll_no);
{ printf("\nEnter Name: ");
int roll_no; flushall( );
char name[50]; gets(s[i].name);
int m1, m2; printf("\nEnter marks:");
};
scanf("%d%d", &s[i].m1, s[i].m2);
typedef struct student STUD;
}
printf("\n\n\nRecords are:");
void main()
for(i=0; i<size; i++)
{
{
STUD s[50];
int i, size; printf("\nRoll no.: %d", s[i].roll_no);
printf("\nEnter no. of records: "); printf("\nName: %s", s[i].name);
scanf("%d", &size); printf("\nMarks:%d %d", s[i].m1, s[i].m2);
printf("\nEnter %d records:", size); }
getch( );
}
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
Structure to Pointer
#include<stdio.h> printf("\nEnter Marks:");
#include<conio.h> scanf("%d%d", &s.m1, &s.m2);
display(&s);
struct stud getch( );
{ }
int roll_no;
char name[50]; void display(struct stud *s1)
int m1, m2; {
}; printf("\nRoll No.: %d", s1->roll_no);
void display(struct stud *); printf("\nName: %s", s1->name);
printf("\nMarks: %d %d", s1->m1, s1->m2);
void main( ) }
{
struct stud s;
printf("\nEnter Roll Number: ");
scanf("%d", &s.roll_no);
printf("\nEnter Name: ");
flushall( );
gets(s.name);
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
Input / Output in C
• There are two types of I/O. • There are different operations
– Console I/O that can be carried out on the
– File I/O file:
• Till now whatever programs we – Creation of new file
have seen, in those programs – Opening an existing file
data vanishes when the – Reading from a file
program ends. So to store the – Writing to a file
data on the disk we need file – Moving to a specific location in
I/O operations. the file
• All the data on the disk is – Closing a file
stored in binary form. But the
process of storing data varies
from OS to OS. The
programmer uses library
function in a particular OS to
perform I/O.
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
void main( )
{
FILE *fs;
fs = fopen("Source.txt", "rb");
if(fs == NULL)
{
puts("Cannot open source file");
exit(1);
}
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
www.ecti.co.in
C Programming
Debugging an “argc-argv” Program
Step 1
www.ecti.co.in
C Programming
Step 2
www.ecti.co.in
C Programming
Step 3
www.ecti.co.in
C Programming
Continued..
Execute the program and check the output.
The arguments will be taken as given by you.
NOTE: You can give strings as arguments within “ “.
Make sure that: hi how are you, has 4 arguments whereas: hi
“how are” you has just 3.
www.ecti.co.in
C Programming
END OF BASICS IN C
Thus, the basics of C programming ends here.
We hope you are satisfied with the theory provided.
Feel free to share, distribute or use it in any form you wish to.
IT IS FOR YOU.
www.ecti.co.in
C Programming
END OF BASICS IN C
For advance C programming course or for any doubts in this
tutorial, please contact us on any of the following details:
www.ecti.co.in