C Programming
C Programming
Sunbeam Infotech
Origin and History
created in the 1970's on PDP-11 under
UNIX by Dennis Ritchie at AT&T Bell
Labs
many ideas came from type less languages
BCPL and B
ANSI standard emerged in 1988-1989
C is a freeform middle level language
It is quite compact as it is a One man
language
Sunbeam Infotech
What is C?
General purpose programming language
Relatively low-level
Fundamental types are characters, integers
and floating point numbers
Hierarchy of derived types in pointers,
arrays, structures and unions
Provides control-flow constructs for well
structured programs
Functions allow complex problems to be
broken down into smaller, more
manageable pieces
Sunbeam Infotech
What is C? (Contd.)
Provides no operations to deal with
composite objects like strings (but has rich
standard library of functions)
Provides no input/output facilities
(provided instead by standard library)
Highly portable across operating systems
and machine types
Highly extensible - power of language
easily extended by data types, macros and
functions provided by user libraries and
header files
Sunbeam Infotech
Strengths
Low-level nature makes it very efficient
Language itself is very readable
Many compilers available for a wide range
of machines and platforms
Standardization improves portability of
code
Efficient in terms of coding effort needed
for a wide variety of programming
applications
Sunbeam Infotech
Simple C Program
1. /*Calculate Area of Rectangle*/
2. #include <stdio.h>
3. void main()
4. {
5. int length = 10, breadth = 7, area;
6. area = length * breadth;
7. printf("Area is %d\n", area );
8. }
Sunbeam Infotech
C tokens
Keywords
Constants
Special symbols
Identifiers
Operators
Sunbeam Infotech
Constants
Numeric constants
– Integer constants
Decimal
Octal
Hexadecimal
– Real constants
floating point form
exponential form
Character constants
Single character constants
String constants
Sunbeam Infotech
C Identifiers
Identifiers give names to variables,
functions, defined types and preprocessor
macros
Formed from letters, digits and
underscores
First character must be letter or
underscore (but names beginning with
underscore normally reserved for internal
compiler use)
Case-sensitve (upper and lower case
letters are different)
Sunbeam Infotech
Declaring variables
Must be declared before first use
Format of statement declaring variable(s) is
modifier type varname1;
Initial value may be specified when variable is
declared (otherwise initial value may be
unpredictable)
int x = 5;
For local variables, declaration statements
must be placed at the beginning of block or
function
Sunbeam Infotech
printf
printf is a standard library function used to
write formatted output to the standard
output device (usually the screen)
Requires header file stdio.h
Format printf( formatstring [, value ] ... );
Should have one format specifier for each
value listed, and types should match
Example - printf(“Value = %f”,temp);
Sunbeam Infotech
scanf
scanf is a standard library function used to
receive formatted input from the standard
input device (usually the screen)
Requires header file stdio.h
Format scanf( formatstring [, value ] ...
);
Should have one format specifier for each
address passed, and types should match
Example - scanf(“%f”,&temp);
Sunbeam Infotech
C operators
sizeofOperator
Mathematical Operators
Assignment & shorthand Operators
Relational Operators
Logical Operators
Conditional Operator
Bitwise Operators
Sunbeam Infotech
Format specifier for printf( )
A format specification, which consists of optional
and required fields, has the following form:
Sunbeam Infotech
Format specifier for scanf( )
A format specification, which consists of optional
and required fields, has the following form:
Sunbeam Infotech
Operators precedence chart
Symbol Meaning Associativity
( ) function call
[ ] array element
pointer to structure left to right
->
member
. structure or union member
Sunbeam Infotech
Operators precedence chart
Symbol Meaning Associativity
+ - unary plus or minus
++ -- pre increment / decrement
! ~ logical & bitwise NOT
* indirection right to left
& address of
Sizeof sizeof
(type) typecast
Sunbeam Infotech
Operators precedence chart
Symbol Meaning Associativity
* / % multiplication, division,
modulus
+ - addition, subtraction
>> << right shift, left shift left to right
< >
relational inequalities
<= >=
== != relational equal, not equal
Sunbeam Infotech
Operators precedence chart
Symbol Meaning Associativity
& bitwise AND
^ bitwise exclusive OR
| bitwise OR left to right
&& logical AND
|| logical OR
? : conditional right to left
Sunbeam Infotech
Operators precedence chart
Sunbeam Infotech
Control Statements in C
Sunbeam Infotech
Control Flow Overview
C statements for decision/selection
– if...else
– switch...case
C statements for iteration (looping)
– for
– while
– do...while
C statements for jump
– break / continue
– return
– goto
Sunbeam Infotech
if statement
if ( expression ) if ( expression ) {
{ stmt1_1
stmt1_1 stmt1_2… }
stmt1_2… else {
} stmt2_1
stmt2_2… }
Expression condition
true expression evaluates to nonzero
value
false expression evaluates to zero value
Sunbeam Infotech
Executes stmt1 if expression is true (not
zero) When else is present executes stmt2
if expression is false (zero)
expression may be built using relational or
mathematical operators
{ } braces are optional and used to group
statements into block
More than one conditions may be checked
simultaneously using Logical operators
Sunbeam Infotech
Conditional operator
Evaluates to either of two values based on
a logical expression
condition ? stmt1 : stmt2
stmt1 is executed if condition is true
else stmt2 is executed.
e.g. x = ( a > b ) ? a : b; /*max of a or
b*/
Actually an expression, not statement, so it
evaluates to certain value & can be used as
putchar( ( Hide = 'Y' ) ? '*' : ch );
Sunbeam Infotech
Nesting if s
/*Finding maximum of 3 numbers*/
if(num1>num2) {
if(num1>num3)
max=num1;
else
max=num3;
}
else {
if(num2>num3)
max=num2;
else
max=num3;
} Infotech
Sunbeam
Using logical operators
/* Finding maximum of three numbers */
if(num1>num2 && num1>num3)
max=num1;
if(num2>num1 && num2>num3)
max=num2;
if(num3>num2 && num3>num1)
max=num3;
printf(“Max = %d”,max);
Sunbeam Infotech
switch statement
switch( expression )
{
case constant-expr1: stmt ...
break;
case constant-expr2: stmt ...
break; . .
.
default: stmt …
}
Sunbeam Infotech
Expression must be integer one
Sunbeam Infotech
Operator ++ / --
Post Increment/Decrement
x++ => use old value of x, then increment x
y-- => use old value of y, then decrement y
Pre Increment/Decrement
++x => increment x, then use new value
--y => decrement y, then use new value
Operators increment or decrement value of
variable by 1.
Sunbeam Infotech
for statement
• Syntax :
for (initialization;condition;modification)
{
stmt1;
stmt2;
}
• /*example*/
for(cnt=1 ; cnt<=10 ; cnt++)
{
printf(“%d\n”,cnt);
}
Sunbeam Infotech
for statement
1. Evaluates initialization
expression, if present
for(
2. Evaluates condition
initialization; expression, if present
condition; 3. If condition is true (not
modification zero) or omitted,
) executes stmt once and
{ proceed to next step;
stmt1; otherwise exits from
loop
stmt2;…
4. Evaluates modification;
}
5. Jump to step 2
Sunbeam Infotech
do...while statement
Used to repeat a statement (or block) while
an expression is true (not zero)
do {
stmt..
initialization / modification;
} while ( condition );
Similar to while except stmt always
executes at least once - test for repeating
done after each time stmt is executed
Sunbeam Infotech
Infinite loop
while(1){
…
}
for(j=0; ;j++) {
…
}
Sunbeam Infotech
break statement
In for, while, and do...while loops, break
exits from the lowest-level loop in which it
occurs
Used for early exit from loop, or for
exiting a infinite loop
Sunbeam Infotech
continue statement
The continue statement cause immediate
loop iteration, skipping the rest of the loop
statements
Jumps to the loop test when used with
while or do
Jumps to loop increment, then test when
used with for
Does not exit the loop (unless next loop
test is false)
Sunbeam Infotech
Functions
The proper use of functions key to
successful C programming
Function is building block of good top-
down, structured code
function as a "black box"
Sunbeam Infotech
Using Functions
Prototype - Declaring, specifying return
value type, type and number of arguments
rettype fnname (argtype argname...
);
Call - Invoking, passing arguments
fnname ( argname ... ) ;
Definition - accessing arguments,
processing and returning a value
rettype fnname ( argtype argname ... )
{
stmt…
}
Sunbeam Infotech
Function Arguments must match
Sunbeam Infotech
Type and number of arguments should
match the function declaration
Return statement specifies return value, if
any, and returns control to the point from
which the function was invoked
Function's return value can be ignored
(statement with no assignment)
Many functions that a C programmer
invokes are in standard or user libraries
and are not defined in the source program
Function cannot be defined within a
function (can't nest definitions)
Sunbeam Infotech
Recursion
Function calling itself is called as recursive
function.
For recursive function terminating
condition must be given.
If terminating condition is not given
properly, then stack overflow occurs.
Sunbeam Infotech
Storage Classes
auto
register
static
extern or global
Sunbeam Infotech
Variable scope and lifespan
Scope refers to where in a program a
particular variable is known
Lifespan refers to how long a variable
retains its storage
Global variables and static variables retain
their storage through program execution
Local variables (auto) are allocated off the
stack and retain their storage only while
the block in which they are declared is
executing
Sunbeam Infotech
Storage classes
Default
Variable Keyword Scope Life
Initial
Local auto garbage block block
Sunbeam Infotech
Pointers
Sunbeam Infotech
Machine
instructions
that compiler
generates use the
address to access
memory, not the
variable name.
float Duh =
3.142;
long Hah = 158;
char Ick = 'M';
Sunbeam Infotech
Pass by address
void sumpro(int n1,int n2, int *ps, int *pp);
void main() {
int num1=10, num2=20, sum, pro;
sumpro(num1,num2,&sum,&pro);
printf(“sum=%d pro=%d”,sum,pro);
}
void sumpro(int n1,int n2, int *ps, int *pp){
*ps = n1+n2;
*pp = n1 * n2;
}
Sunbeam Infotech
Why pointers??
• To return more than one value from a
function
• To pass arrays &structure more
conveniently to functions.
• Concise and efficient array access
• Access dynamic memory
• To create complex data structures
• To communicate information about
memory.
Sunbeam Infotech
What is a Pointer?
A Pointer is a variable that stores address
of a memory location.
z z_ptr
Sunbeam Infotech
Operator & and *
& called as direction or reference or
address of operator and used to get address
of any variable
Sunbeam Infotech
Pointer arithmetic
When pointer is incremented or
decremented by 1, it changes by the size of
data type to which it is pointing (scale
factor)
When integer ‘n’ is added or subtracted
from a pointer, it changes by ‘n’ times size
of data type to which pointer is pointing.
Multiplication or division of any integer
with pointer is meaning less.
Sunbeam Infotech
Pointer arithmetic
Addition, multiplication and division of
two pointers is meaning less.
Subtraction of two pointers have meaning
only in case of arrays.
Sunbeam Infotech
Pointer to pointer
The pointer that stores address of another
pointer variable is called as ‘pointer to
pointer’.
Example :-
int x=10; int *px=&x;
int **ppx=&px;
printf(“%d”,**ppx);
Sunbeam Infotech
Pointer Concepts
void pointer
NULL pointer
Pointer and ++
Level of indirection
Pointer to function
Sunbeam Infotech
File Icons
Sunbeam Infotech
Compiling C Program
Source code ( .C )
Preprocessor
Compiler
Sunbeam Infotech
Macro
#define AND &&
#define PI 3.1415
#undef macroname
Sunbeam Infotech
File Inclusion
#include <stdio.h>
#include “myheader.h”
#include “c:\\folder\\myheader.h”
Sunbeam Infotech
Conditional compilation
#if
#else
#elif
#endif
#ifdef
#ifndef
INT_MAX
CHAR_MAX
Sunbeam Infotech
Other Directives
#error
#line
#pragma
Stringizing operator #
Sunbeam Infotech
1D Array - Fig
arr 0 1 2 3 4
0x100 1 2 3 4 5
0x100 0x100 0x102 0x104 0x106 0x108
arr[0] arr[1] arr[2] arr[3] arr[4]
&arr[0] = 0x100
&arr = 0x100
arr = 0x100
*arr = 1
Sunbeam Infotech
1D Array - Syntax
void main() {
int arr[5], j;
printf(“Enter 5 elements..”);
for(j=0;j<5;j++)
scanf(“%d”,&arr[ j ]);
for(j=0;j<5;j++)
printf(“\n%d”,arr[ j ]);
}
Sunbeam Infotech
1D Array & pointers - Syntax
void main() {
int arr[5], *ptr, j;
ptr = arr ;
printf(“Enter 5 elements..”);
for(j=0;j<5;j++) {
scanf(“%d”, ptr);
ptr ++;
}
ptr = arr;
for(j=0;j<5; j++, ptr++)
printf(“\n%d”,*ptr);
}
Sunbeam Infotech
Array & pointer
int arr[5] ;
int *ptr=arr;
*(ptr+i) == ptr[i]
*(i+ptr) == i[ptr]
Sunbeam Infotech
Passing array to function
Arrays are passed to function by address.
The address of starting element of array (
Base address ) is passed to the function.
The address is collected in a pointer.
We can use pointer as well as array
notation to access array elements in the
function.
Sunbeam Infotech
1D array of characters
char arr[5] = { ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ };
int j;
for(j=0; j<5; j++)
printf(“%c”,arr[ j ]);
Sunbeam Infotech
String
String is an array of characters that
terminates with null character (‘\0’).
/*Example*/
char arr[5] = “abcde”;
int j;
for(j=0; j<5; j++)
printf(“%c”,arr[ j ]);
Sunbeam Infotech
String Input/Output
char str[20];
scanf(“%s”,str); /*Input*/
printf(“%s”,str); /*Output*/
char str[20];
gets(str); /*Input*/
puts(str); /*Output*/
Sunbeam Infotech
String functions
String operations are done by library
functions.
The functions are declared in “string.h”
The functions are –
o strlen
o strcpy
o strcat
o strcmp
o strrev
Sunbeam Infotech
Array of pointers
void main() {
char *arr[]={ “mon”, “tue”, “wed”, “thr”,
“fri”, “sat”, “sun” };
int j;
for(j=0;j<7;j++)
puts(arr[j]);
}
Sunbeam Infotech
Standard main() prototypes
int main();
int main(int argc, char *argv[]);
int main(int argc,char*argv[],char*envp[]);
argc represents number of arguments
passed to program when it is executed
from command line.
argv represents argument vector or
argument values.
envp represents system information.
Sunbeam Infotech
Command Line Arguments
The values passed to program when it is
executed on command line is called as
“command line arguments”.
These values are get collected in array of
character pointer argv.
The count of arguments get stored in argc.
The first argument in argv is always name
executable file.
Sunbeam Infotech
Command line arguments – fig
argc argv If Demo.exe is executed like -
4 100
1000 500 Demo.exe ABCD Hello 1234
argv[0] 100 10 d e m O . e x e \0
10 11 12 13 14 15 16 17 18
argv[1] 102 40 A B C D \0
40 41 42 43 44
argv[2] 104 50 H e l L 0 \0
50 51 52 53 54 55
argv[3] 106 60 1 2 4 \0
60 61 62 63
argv[4] 108 0
Sunbeam Infotech
Dynamic memory allocation
void* malloc(int size);
void* calloc(int count,int elesize);
void* realloc(void *memblock,int size);
The address returned by these functions
should be type-casted to the required
pointer type.
Calloc() allocates an array in memory with
elements initialized to zero.
Changes size of allocated memory block.
Sunbeam Infotech
1D Array Revising
0 1 2 3 4
1 2 3 4 5
0x100 0x102 0x104 0x106 0x108
arr[0] arr[1] arr[2] arr[3] arr[4]
arr
Sunbeam Infotech
2D array
Two dimensional array is defined as 1-D
array of 1-D arrays.
/*Example*/
int arr[3][2]={{1,2},{3,4},{5,6}};
int i, j;
for ( i=0; i<3 ;i++ )
for( j=0; j<2; j++)
printf(“%d”,arr[i][j]);
Sunbeam Infotech
2D Array - Fig
row=0 row=1 row=2
col=0 col=1 col=0 col=1 col=0 col=1
1 2 3 4 5 6
100 102 104 106 108 110
Sunbeam Infotech
2D array of characters
void main() {
char arr[3][8] = { “abc”, “def”, “xyz” };
int j;
for (j=0; j<3; j++)
printf(“%s”,arr[j]);
}
Sunbeam Infotech
Structure
Structure is collection of non-similar data
elements in contiguous memory locations.
Each element has its own storage.
Structure is user defined data type.
Members of structures can be accessed
using “.” operator with structure variable.
Members of structures can be accessed
using “” operator with pointer to
structure variable.
Sunbeam Infotech
Structure – Syntax – 1
/*Structure declarations are generally done
before main i.e. global declaration. We can
also do it in a function.*/
struct student {
int roll_no, std;
char name[10];
float avg;
};
Sunbeam Infotech
Structure – Syntax – 2
/*initializing structure variable at its
declaration*/
void main() {
struct student s1={424,10,”Nilesh”,78.67};
printf(“size=%d”,sizeof(s1));
printf(“roll=%d,std=%d,nm=%s,avg=%f”,
s1.roll, s1.std, s1.name, s1.avg);
}
Sunbeam Infotech
Structure - Fig
s1.roll s1.std s1.name s1.avg
424 10 “Nilesh” 78.67
100 102 104 114
s1
Sunbeam Infotech
Pointer to Structure
void main() {
struct student s1={424,10,”Nilesh”,78.67};
struct student *ptr = &s1;
printf(“size=%d”,sizeof(ptr));
printf(“roll=%d,std=%d,nm=%s,avg=%f”,
ptrroll, ptrstd, ptrname, ptravg);
}
Sunbeam Infotech
Concepts
Passing structures to function
o Pass by value
o Pass by address
Anonymous structures
Sunbeam Infotech
Array of structure
S[0] S[0] S[0] S[0] S[1] S[1] S[1] S[1]
.roll .std .name .avg .roll .std .name .avg
424 10 “Raj” 78.67 425 10 “Ram” 78.67
100 102 104 114 118 120 122 132
S[0] S[1]
S
Sunbeam Infotech
Union
Union is collection of similar data
elements like structures. But all data
elements share same memory location.
union test { int x;
float y;
char ch; }
sizeof (union test) = 4;
We can use only one member at a time.
Sunbeam Infotech
Unions and structure
Unions and structures can be nested within each
other.
union REGS {
struct WORDREGS {
unsigned char al, ah, bl, bh;
unsigned char cl, ch, dl, dh;
}x;
struct BYTEREGS {
unsigned int ax, bx, cx, dx;
unsigned int si, di, cflag, flags;
}h;
};
Sunbeam Infotech
Enumerations
Enums are basically integer & used for defining
const integer. It improves readability of program.
enum color {
RED, BLACK, GREEN=5, YELLOW
};
enum color c=RED;
printf(“size = %d”,sizeof ( c ));
switch(c){
case RED: printf(“Red”); break;
case BLACK: printf(“black”): break;
}
Sunbeam Infotech
File
Input - Output
Formatted IO UnFormatted IO
Sunbeam Infotech
High Level File input/output
Must open file first to set file pointer
Must pass file pointer to file access functions
Need to close file when done
Functions
• fopen, fclose, freopen
• fseek , ftell
• rewind
• remove, rename
• fflush
Sunbeam Infotech
Time complexity
Sort Algo Tw(n) Ta(n)
Selection Sort (n2) (n2)
Sunbeam Infotech