C Programming
Introduction
Developed by Dennis Richie
Developed at Bell Lab in U.S.A. in 1972
Derived from a language known as BCPL
(Basic Combined Programming Language)
Program Development Cycle
Creating Source Code
Compiling Source Code
Linking the source code
Running the executable file
Program Development Cycle
Written in
C Source Pre- Object
Editor processed Linker
Program Code Code
Code
Compilation
Executable
Code
Structure of C program
Documentation Section
Link Section
Definition Section
Global Declaration Section
Function Section
Main Function()
{
Declaration
Executable Part
}
Sub Program Section
{
Function 1()
…
Function n ()
}
Variables, Data Types, Operators,
Expression
Character Set
Upper case and lowercase characters, 0-9
digits, special characters, white spaces
1. Alphabets A-Z, a-z
2. Digits 0-9
3. Special Characters #, @, &, %, _,-
4. White Space Characters blank space, tab,
new line
C Tokens
C Token
String Other
Identifiers Keywords Constants Operators
Literals Symbols
Identifiers and Keywords
Identifier is a user defined name given to a
program element – variable, functions,
symbolic constants
Rules for naming identifier :-
1) Must be sequence of alphabets & digits
2) Must begin with alphabet
3) No special symbol except (_) is allowed
4) Reserve word should not used as identifier
5) C is case sensitive
6) For naming maximum 32 characters are
allowed
Keywords
Keywords are reserve words & predefined by
language. They can not be used by
programmer in any other than specified by
syntax. C provides 32 keywords.
Constants
Constants refers to fixed value that do not
changes during program execution. They can
be classified as :
1) integer constants
2) floating point constants
3) character constants
4) string literals
Variables
A variable name is an identifier or symbolic
name assigned to the memory location where
data is stored. A variable ca have only one
value assigned to it at any given time during
program execution. Its value may change
during execution of the program.
Data Types in C
Qualifiers
The size qualifiers are :
short
long
Sign qualifiers
signed
unsigned
Scope of Variables
Local
Global
Local Variable
main()
{
int a, b;
}
void add(int x, int y)
{
int sum=0;
sum=x+y;
printf(“\n Sum = %d”, sum);
}
Global Variable
int a, b;
main()
{
printf (“\n in main a=%d”,a);
}
void val(int x)
{
a=x;
printf(“\n in Function = %d”,a);
}
Opeators
Arithmetic
Relational
Logical
Assignment
Increment/ Decrement
Conditional
A=10
B=10
A==B
Logical
&&
||
!
And &&
if(age>18) &&(citizen==“Indian”)
{
printf(“Elegible for voting”);
}
else
{
printf(“\n Not eligible for voting”);
}
Or ||
If(day==“Saturday” ) || (day==“Sunday”)
{
printf(“Its holiday”);
}
else
{
printf(“Working day”);
}
!not
If(n!=0)
{
printf(“%d”,n);
}
Else
{
printf(“Its zero”);
}
Increment/decrement
++
i=1
i++
I is 2
i+2
I is 4
--
J=5
J--
J is 4
Conditional operators
Ans= (condition) ? Opt1 :opt2
A=15
B =5
Z=A>B ? A:B
sizeof
Int a;
Sizeof(a)
2
Input/Output Statement in C
Input means to provide the program with some data to be
used in the program and Output means to display data on the
screen or write the data to a printer or a file.
The C programming language provides standard library
functions to read any given input and to display data on the
console.
The functions used for standard input and output are
present in the stdio.h header file. Hence to use the
functions we need to include the stdio.h header file
#include<stdio.h>
Following are the functions used for standard input and
output:
printf() function - Show Output
scanf() function - Take Input
getchar() and putchar() function
gets() and puts() function
printf() function
The printf() function is the most used function in the C
language. This function is defined in the stdio.h header
file and is used to show output on the console (standard
output).
This function is used to print a simple text
sentence or value of any variable which can be
of int, char, float, or any other datatype.
Format Specifiers
To print values of different datatypes using
the printf() statement, we need to use format
specifiers, like we have used in the code examples
above.
Also, when we take input from user using
the scanf() function, then also, we have to specify
what type of input to expect from the user using
these format specifiers.
Datatype Format Specifier
int %d, %i
char %c
float %f
double %lf
short int %hd
unsigned int %u
long int %li
unsigned long int %lu
signed char %c
unsigned char %c
long double %Lf
scanf()
When we want to take input from the user, we use
the scanf() function. When we take input from the user,
we store the input value into a variable.
The scanf() function can be used to take any datatype
input from user, all we have to take care is that the
variable in which we store the value has the same
datatype.
getchar() & putchar()
The getchar() function reads a character from
the terminal and returns it as an integer. This
function reads only a single character at a
time.
The putchar() function displays the character
passed to it on the screen and returns the
same character. This function too displays
only a single character at a time.
In case you want to display more than one
character, use putchar() method in a loop.
gets() & puts()
The gets() function reads a line from stdin(standard
input) into the buffer pointed to by str pointer, until
either a terminating newline or EOF (end of file)
occurs.
The puts() function writes the string str and a trailing
newline to stdout.
Branching Statements
In the term software or computer programming, it has a
set of instruction (in simple or complex form) called
program. These instructions are also called statements,
which occurs sequentially or in either conditional way or in
the iterative way. To handle such types of statements some
flow controls required. These flow controls are
called Control Statements
In other words, the control statements are used to control
the cursor in a program according to the condition or
according to the requirement in a loop. There are mainly
three types of control statements or flow controls.
Types of Control Statements
Branching
Looping
Jumping
Branching Statements
Simple if statement
if—else
Nested if
if—else ladder
if statement
The if statement is a powerful decision
making statement which can handle a single
condition or group of statements. These have
either true or false action....
When only one condition occurs in a
statement, then simple if statement is used
having one block.
if statement
Syntax
if (condition)
{
instruction;
}
if.. else statement
This statement also has a single condition
with two different blocks. One is true block
and other is false block...
if.. else statement
Syntax
if (test-expression)
{ True block of statements }
else
{ False block of statements }
Statements;
Nested if
When a series of decision is required, nested if
-else is used. Nesting means using one if-
else construct within another one.
Nested if
if (test - expression 1)
{ statement1; }
else if (test - expression 2)
{ Statement2; }
else if (test - expression 3)
{ Statement3; }
else if (test - expression n)
{ Statement n; }
else { default; }
Statement x;
switch
Syntax:=
switch (expression)
{
case constant1:
statements;
break;
case constant2:
statements ;
break;
. . . Default:
default:
statements;
}
switch
Looping Statement
The looping can be defined as repeating the
same process multiple times until a specific
condition satisfies.
The looping simplifies the complex problems
into the easy ones. It enables us to alter the
flow of the program so that instead of writing
the same code again and again, we can
repeat the same code for a finite number of
times.
Types of looping statement
There are three types of loops in C language
that is given below:
do while
while
for
while in C
The while loop in c is to be used in the
scenario where we don't know the number of
iterations in advance. The block of
statements is executed in the while loop until
the condition specified in the while loop is
satisfied. It is also called a pre-tested loop.
while
Syntax
Assignment;
while(condition)
{ Statements;
......
Increment/decrements (++ or --);
}
while
do while
Unlike for and while loops, which test the
loop condition at the top of the loop,
the do...while loop in C programming checks
its condition at the bottom of the loop.
A do...while loop is similar to a while loop,
except the fact that it is guaranteed to
execute at least one time.
do .. while
do
{
statement(s);
} while( condition );
for
A for loop is a repetition control structure that
allows you to efficiently write a loop that
needs to execute a specific number of times.
for
for ( init; condition; increment )
{
statement(s);
}
array
An array is defined as the collection of similar
type of data items stored at contiguous
memory locations. Arrays are the derived data
type in C programming language which can
store the primitive type of data such as int,
char, double, float, etc.
Properties of Array
Each element of an array is of same data type
and carries the same size, i.e., int = 4 bytes.
Elements of the array are stored at
contiguous memory locations where the first
element is stored at the smallest memory
location.
Elements of the array can be randomly
accessed since we can calculate the address
of each element of the array with the given
base address and the size of the data
element.
Adavatages
Code Optimization: Less code to the access
the data.
Ease of traversing: By using the for loop, we
can retrieve the elements of an array easily.
Ease of sorting: To sort the elements of the
array, we need a few lines of code only.
Random Access: We can access any element
randomly using the array.
Disadvantages
Fixed Size: Whatever size, we define at the
time of declaration of the array, we can't
exceed the limit.
declaration
data_type array_name[array_size];
int marks[5];
Array initilization
The simplest way to initialize an array is by
using the index of each element. We can
initialize each element of the array by using
the index.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Charcter array
String is a sequence of characters that are
treated as a single data item and terminated
by a null character '\0'. Remember that the C
language does not support strings as a data
type. A string is actually a one-dimensional
array of characters in C language. These are
often used to create meaningful and readable
programs.
Character Array
Example
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello";
String Handling Functions
Sr. Function name description
no.
1 strlen() Find length of string
2 strcpy() Copying string
3 strcmp() Comparison of string
4 strcat() Concatenation of String
5 strrev() Reverse of string
6 strlwr() Convert string to lower case
7 strupr() Convert string to upper case