PROGRAMMING with C
Basic Concept of Programming
Evolution of Programming!
HARDWARE
• Inputs To pin
outs
• Processed
using Gates
Assembly
language
• Added Strings
• Assembler
Directives
High Level
Languages
• Compilers
• Interpreters
A Basic C Program
#include<stdio.h>
void main(){
int no, index;
char * name[10];
printf(“ENTER NO OF STUDENTS:”);
scanf (“%d”, &n);
printf(“ENTER STUDENTS NAME:n”);
for(index=1;index<= no; index=index+1){
scanf(“%s”, name[index]);
}
printf(“NAME STARTS WITH ‘A’ ARE n:”);
for(index=1;index<= no; index=index+1){
if( name[index][0]==‘A’ || name[index][0]==‘a’){
printf(“t %s n”, name[index]);
}
}
}
How Programming works?
COMPILER
• Create a Program and COMPILE it
• WE will get an object code
OS
• On call, OS places it to RAM
• OS Pass Program ID to Scheduler
PROCESSOR
• Exchange values/data form I/O
• Execute Process
• Generates output
# Byte Reservation for Data Types
• For each variable to be stored, we have to allocate some
memory with specified size in Byte.
• 1 Byte=8 bits
• We can store characters from ANSI defined set.
• We can store Integers
• We can sore Floating Points/ Decimal format Numbers
• We can store Memory Addresses.
• Some programming languages use #void as a data type which
holds nothing(if variable) or holds anything(if data type)
ByteReservationChart
# One Thing to Notice
Sample Code:
signed int i=100
for(; i>0;i++);
printf(“%d”, i);
// In this pseudo code we assume, int takes exactly 1 byte
Output: _____?
# One Thing to Notice
Sample Code:
signed int i=100
for(; i<0;i++);
printf(“%d”, i);
// In this pseudo code we assume, int takes exactly 1 byte
Output: -128 !
// ranges from -128 to 127
So this loop go from: +100, +101, +102,………., +126, 127, -128;
STRUCTURE OF C PROGRAM
How to write a C Program?
32 Keywords forms the whole C
continue for auto int signed return
break while extern char unsigned void
case do static float enum goto
const if register double struct typedef
switch else long short union near
default volatile
>> This small keyword set makes the whole C powerful.
>> Its Libraries and Headers helps to simplify the programming.
>> The concept of POINTER and OPERATORS set helps to work in Hardware Level.
Operators in C.
DOMAIN OPERATORS
Arithmetic + - * / % ++ --
Relational == != > < <= >=
Logical && || !
Bitwise & | ^ ~ << >>
Assignment = += -= *= /= %= <<= >>=
Misc. sizeof() & * ?:
Arithmetic Operators : used in expressions
Relational Operators : used in relating values | returns Boolean value
Logical Operations : used in constructing Logical relations between Boolean value
returns Boolean value
Bitwise Operators : Manipulates data in Bit level ( 1011 1001)
Assignment Operators: Assigns R Value to L value
Sizeof() : Returns Size of data type in byte
& : Gives address of specified variable (Pointer)
* : Gives value at specified address (Pointer)
?: : inline conditions Syntax: (<condition>)?<if true>:<else>;
OPERATOR PRESIDENCE
• Right to Left – Start evaluate from Right
• Unary Operators
• Conditional Operators
• Assignment Operators
• Left To Right
• Everything Else such as Bitwise, Arithmetic etc.
CONTROL - FLOW
Program
Control Flow
Sequential Branching
Conditional
If else Switch
Unconditional
Goto
Iterative
For While Do while
VARIABLES
• Names given to those reserved memory location.
• In C ; a variable name have some constrains as per ANSI C regulations Rules
For Constructing Variable Name
• Characters Allowed :
• Underscore(_)
• Capital Letters ( A – Z )
• Small Letters ( a – z )
• Digits ( 0 – 9 )
• Blanks & Commas are not allowed
• No Special Symbols other than underscore(_) are allowed
• First Character should be alphabet or Underscore
• Variable name Should not be Reserved Word
• Variable have 2 parts
• R-value - [CONTENT of variable]
• L-value - [Address of Location]
Attributes of C Variable :
• 1.Name of Variable
• Variable name is only the name given to the “Memory address”.
• Variable name maps into “Address inside” and then by considering mapped address compiler
processes data.
• 2.Value inside Variable
• Depending on the type of Variable we can store any value of appropriate data type inside
Variable.
• 3.Address of Variable
• Variable can hold data ,it means there should be a container. So container must have Starting
Address.
• Address of variable = Starting Address of allocated Memory
• 4.Type of Variable
• Type of variable tells compiler that – “Allocate memory for data of Specified type“.
• 5.Size of Variable
• We can use sizeof operator to calculate size of any data type.
Main Function
• Till now we had use only one function. That is main();
• Main() is the only function which will be automatically called
on loading a program file
• There can be files without main function. In such cases, no
function will be called by default and nothing will execute until
we specifically call a function.
• So main() have nothing special than any other functions
• Compiler is the one which causes execution of main program
on call.
FUNCTION
• We can create enormous functions in a file.
• SYNTAX:
return type FUNCTION_NAME ( Parameter LIST)
{
……………………………
…………body…………
……………………………
return value;
}
int power( int a, int b) {
int result, i;
result=a;
for ( i=2; i<b; i++) {
result *= a;
}
return result;
}
void main(){
int p;
p = power(5,3);
printf(“%d”, a);
}
Local and Global Variables
• Local variables are variables inside a function can be used only
inside it.
• A variable declared out side the functions is known as Global
variables and can be used by any function. Changing value at
any function will change it globally.
Scope Lifetime and Visibility
• Each variable have its own scope, lifetime and visibility.
• SCOPE :- The region at which the value of a variable
can be used/Variable is in active state.
• LIFETIME :- The time period, where a variable is stored in
memory / RAM.
• VISIBILITY :- The set of program lines where a variable’s
value can be used / Variable is in active or
passive State.
Local and Global Variables
VARIABLE INSIDE
CALLED FUNCTION
GLOBAL VARIABLE VARIABLE INSIDE
CALLER FUNCTION
SCOPE Only Inside Local
Function
Everywhere inside
the program
Inside Caller and
Called function
LIFETIME From beginning of
function to end of
that local function.
From beginning of
program to end of
that program.
From beginning of
caller function to
end of that
function.
VISIBILITY Only inside Local
Function
Everywhere inside
the program
Only inside Caller
function
Data Structures
Array
Stack
Queue
Linked
List
Data Structures
• ARRAY – Data is stored in continuous memory locations
• LINKED LIST – Data is stored in separate pieces of memory
blocks and is linked to next block.
• STACK – Structures follow LAST IN FIRST OUT principle.
• QUEUE – Structures follow FIRST IN FIRST OUT principle.
Array
• “ int a[10];” initializes a location of 10*sizeof(int) space in
memory {10x 4bytes = 40 bytes};
• Each can be accessed by a[0], a[1], a[2], ……, a[8], a[9];
• Actually ‘var a’ become the pointer to the block of memory of
size 40 bytes.
• 0,1,2,3…. Are known as INDEX of array which are from
0 to (n-1);
STRING
• Strings are handled as an array of (char) type.
• Last character of array will be ‘0’
• Since an array, strings cannot be handled using normal
assignment operators or such;
• Header File Contains the string handling functions
#include<string.h>
• strcpy()
• strcat()
• strlen()
• strcmp()
• strchr()
• strstr()
Structure and Union
• Structure and Union are two type of user definable data
structures..
• Structure can be utilized for creating records; where Union can
be used for storing multiple type of data with only one data
per time.
TYPEDEF…
• Typedef is actually a keyword for assigning data types to a
Variable name;
|
| typedef unsigned int ROLLNO
|
DEFINE
• Typedef is actually a keyword for assigning permanent values
to a CONSTANT;
|
| #define PI 3.141521
|
#Type Casting
• CHAR and INT are interconvert able, since in ASCII Set,
Character is bind to an integer no between 0 and 255.
• To convert an expression to another type; we can use type cast.
• int x=3,y=2;
• printf(“ %.3fn”, (float) x/y);
• OUTPUT : “1”
• printf(“ %.3fn”, (float) x/y);
• OUTPUT : “1.500”
Weightage of Type Casting
INT
UNSIGNED INT
LONG
UNSIGNED LONG
LONG LONG
UNSIGNED LONG LONG
FLOAT
DOUBLE
LONG DOUBLE
RECURSION
• We know we can call any function from anywhere inside
another function
• In the same way; we can call any function from inside that
function.
• This is known as Recursion.
• This will create infinitely long execution
• In order to prevent that, one who call has to specify an
intelligent condition inside function
FILES AND I/O MANAGEMENT
How C Compiler Seek these things
STARNDERD I/O DEVICES
• STDIN -> Stranded Input Device : KEYBOARD
• STDOUT -> Stranded Output Device : MONITOR
I/O MANIPULATIONS.
• CHARACTER
• int getchar(void);
• int putchar(char c);
• STRING
• char *gets(void);
• int puts(char *s);
• GENERAL
• int scanf(const char *format);
• int printf(const char *format);
[%d, %c, %f, %s, %u, %x, %i,… ]
FILE HANDLERs
• FILE *fopen(const char *filename, const char *mode);
a FUNCTION
r Open file in read mode
w Open empty file in write mode if file not exist: error
a Open file with content in append mode if file not
exist: error; append mode appends data to existing.
r+ Open file in read/write mode mode
w+ Open in write mode; if file not exist: create;
a+ Open in append mode; if file not exist: create;
FILE MANIPULATIONS.
• CHARACTER
• int fgetc (FILE *fp);
• int fputc (int c, FILE *fp);
• STRING
• char *fgets(const char *s, int len, FILE *fp );
• int fputs(const char*c, FILE *fp);
• GENERAL
• int fscanf(FILE *fp, const char *format);
• int fprintf(FILE *fp, const char *format);
DYNAMIC MEMORY MANAGEMENT
Efficiency and Reliability depends on how Dynamic they are..
Memory Allocations
• Concept of HEAP AND STACK Memory
• void *calloc(int len, int size);
• Allocates array of length<-len, and block of size<-size
• Initialize location with 0;
• void free(void *address)
• Frees a piece of memory
• void *malloc(int num*sizeof (datatype))
• Allocates an array of num bytes
• void *realloc(void * address, int newsize)
• Extends parent size
COMMAND LINE ARGUMENTS
Parameters on call concept…
Command Line arguments
• It is possible to pass some values from the command line to your C
programs when they are executed. These values are called command line
arguments and many times they are important for your program especially
when you want to control your program from outside instead of hard coding
those values inside the code.
POINTERS
Hardware Level Thinking…
POINTERS and VOID
• Pointers are variables which stores address of another
memory location.
• Declaration : int *i; char* f; float* m[];
• Data Type Pointers define, which type of data is pointed by it.
• Functions can also be pointed by it.
• void *f; is the type which can hold any pointer;
• Function pointers are pointers to the address of first line of
function.
POINT 2D Array using Pointers
• p[i][j] === *(*(p+i)+j));

C

  • 1.
    PROGRAMMING with C BasicConcept of Programming
  • 2.
    Evolution of Programming! HARDWARE •Inputs To pin outs • Processed using Gates Assembly language • Added Strings • Assembler Directives High Level Languages • Compilers • Interpreters
  • 3.
    A Basic CProgram #include<stdio.h> void main(){ int no, index; char * name[10]; printf(“ENTER NO OF STUDENTS:”); scanf (“%d”, &n); printf(“ENTER STUDENTS NAME:n”); for(index=1;index<= no; index=index+1){ scanf(“%s”, name[index]); } printf(“NAME STARTS WITH ‘A’ ARE n:”); for(index=1;index<= no; index=index+1){ if( name[index][0]==‘A’ || name[index][0]==‘a’){ printf(“t %s n”, name[index]); } } }
  • 4.
    How Programming works? COMPILER •Create a Program and COMPILE it • WE will get an object code OS • On call, OS places it to RAM • OS Pass Program ID to Scheduler PROCESSOR • Exchange values/data form I/O • Execute Process • Generates output
  • 5.
    # Byte Reservationfor Data Types • For each variable to be stored, we have to allocate some memory with specified size in Byte. • 1 Byte=8 bits • We can store characters from ANSI defined set. • We can store Integers • We can sore Floating Points/ Decimal format Numbers • We can store Memory Addresses. • Some programming languages use #void as a data type which holds nothing(if variable) or holds anything(if data type)
  • 6.
  • 7.
    # One Thingto Notice Sample Code: signed int i=100 for(; i>0;i++); printf(“%d”, i); // In this pseudo code we assume, int takes exactly 1 byte Output: _____?
  • 8.
    # One Thingto Notice Sample Code: signed int i=100 for(; i<0;i++); printf(“%d”, i); // In this pseudo code we assume, int takes exactly 1 byte Output: -128 ! // ranges from -128 to 127 So this loop go from: +100, +101, +102,………., +126, 127, -128;
  • 9.
    STRUCTURE OF CPROGRAM How to write a C Program?
  • 10.
    32 Keywords formsthe whole C continue for auto int signed return break while extern char unsigned void case do static float enum goto const if register double struct typedef switch else long short union near default volatile >> This small keyword set makes the whole C powerful. >> Its Libraries and Headers helps to simplify the programming. >> The concept of POINTER and OPERATORS set helps to work in Hardware Level.
  • 11.
    Operators in C. DOMAINOPERATORS Arithmetic + - * / % ++ -- Relational == != > < <= >= Logical && || ! Bitwise & | ^ ~ << >> Assignment = += -= *= /= %= <<= >>= Misc. sizeof() & * ?: Arithmetic Operators : used in expressions Relational Operators : used in relating values | returns Boolean value Logical Operations : used in constructing Logical relations between Boolean value returns Boolean value Bitwise Operators : Manipulates data in Bit level ( 1011 1001) Assignment Operators: Assigns R Value to L value Sizeof() : Returns Size of data type in byte & : Gives address of specified variable (Pointer) * : Gives value at specified address (Pointer) ?: : inline conditions Syntax: (<condition>)?<if true>:<else>;
  • 12.
    OPERATOR PRESIDENCE • Rightto Left – Start evaluate from Right • Unary Operators • Conditional Operators • Assignment Operators • Left To Right • Everything Else such as Bitwise, Arithmetic etc.
  • 13.
    CONTROL - FLOW Program ControlFlow Sequential Branching Conditional If else Switch Unconditional Goto Iterative For While Do while
  • 14.
    VARIABLES • Names givento those reserved memory location. • In C ; a variable name have some constrains as per ANSI C regulations Rules For Constructing Variable Name • Characters Allowed : • Underscore(_) • Capital Letters ( A – Z ) • Small Letters ( a – z ) • Digits ( 0 – 9 ) • Blanks & Commas are not allowed • No Special Symbols other than underscore(_) are allowed • First Character should be alphabet or Underscore • Variable name Should not be Reserved Word • Variable have 2 parts • R-value - [CONTENT of variable] • L-value - [Address of Location]
  • 15.
    Attributes of CVariable : • 1.Name of Variable • Variable name is only the name given to the “Memory address”. • Variable name maps into “Address inside” and then by considering mapped address compiler processes data. • 2.Value inside Variable • Depending on the type of Variable we can store any value of appropriate data type inside Variable. • 3.Address of Variable • Variable can hold data ,it means there should be a container. So container must have Starting Address. • Address of variable = Starting Address of allocated Memory • 4.Type of Variable • Type of variable tells compiler that – “Allocate memory for data of Specified type“. • 5.Size of Variable • We can use sizeof operator to calculate size of any data type.
  • 16.
    Main Function • Tillnow we had use only one function. That is main(); • Main() is the only function which will be automatically called on loading a program file • There can be files without main function. In such cases, no function will be called by default and nothing will execute until we specifically call a function. • So main() have nothing special than any other functions • Compiler is the one which causes execution of main program on call.
  • 17.
    FUNCTION • We cancreate enormous functions in a file. • SYNTAX: return type FUNCTION_NAME ( Parameter LIST) { …………………………… …………body………… …………………………… return value; } int power( int a, int b) { int result, i; result=a; for ( i=2; i<b; i++) { result *= a; } return result; } void main(){ int p; p = power(5,3); printf(“%d”, a); }
  • 18.
    Local and GlobalVariables • Local variables are variables inside a function can be used only inside it. • A variable declared out side the functions is known as Global variables and can be used by any function. Changing value at any function will change it globally.
  • 19.
    Scope Lifetime andVisibility • Each variable have its own scope, lifetime and visibility. • SCOPE :- The region at which the value of a variable can be used/Variable is in active state. • LIFETIME :- The time period, where a variable is stored in memory / RAM. • VISIBILITY :- The set of program lines where a variable’s value can be used / Variable is in active or passive State.
  • 20.
    Local and GlobalVariables VARIABLE INSIDE CALLED FUNCTION GLOBAL VARIABLE VARIABLE INSIDE CALLER FUNCTION SCOPE Only Inside Local Function Everywhere inside the program Inside Caller and Called function LIFETIME From beginning of function to end of that local function. From beginning of program to end of that program. From beginning of caller function to end of that function. VISIBILITY Only inside Local Function Everywhere inside the program Only inside Caller function
  • 21.
  • 22.
    Data Structures • ARRAY– Data is stored in continuous memory locations • LINKED LIST – Data is stored in separate pieces of memory blocks and is linked to next block. • STACK – Structures follow LAST IN FIRST OUT principle. • QUEUE – Structures follow FIRST IN FIRST OUT principle.
  • 23.
    Array • “ inta[10];” initializes a location of 10*sizeof(int) space in memory {10x 4bytes = 40 bytes}; • Each can be accessed by a[0], a[1], a[2], ……, a[8], a[9]; • Actually ‘var a’ become the pointer to the block of memory of size 40 bytes. • 0,1,2,3…. Are known as INDEX of array which are from 0 to (n-1);
  • 24.
    STRING • Strings arehandled as an array of (char) type. • Last character of array will be ‘0’ • Since an array, strings cannot be handled using normal assignment operators or such; • Header File Contains the string handling functions #include<string.h> • strcpy() • strcat() • strlen() • strcmp() • strchr() • strstr()
  • 25.
    Structure and Union •Structure and Union are two type of user definable data structures.. • Structure can be utilized for creating records; where Union can be used for storing multiple type of data with only one data per time.
  • 28.
    TYPEDEF… • Typedef isactually a keyword for assigning data types to a Variable name; | | typedef unsigned int ROLLNO |
  • 29.
    DEFINE • Typedef isactually a keyword for assigning permanent values to a CONSTANT; | | #define PI 3.141521 |
  • 30.
    #Type Casting • CHARand INT are interconvert able, since in ASCII Set, Character is bind to an integer no between 0 and 255. • To convert an expression to another type; we can use type cast. • int x=3,y=2; • printf(“ %.3fn”, (float) x/y); • OUTPUT : “1” • printf(“ %.3fn”, (float) x/y); • OUTPUT : “1.500”
  • 31.
    Weightage of TypeCasting INT UNSIGNED INT LONG UNSIGNED LONG LONG LONG UNSIGNED LONG LONG FLOAT DOUBLE LONG DOUBLE
  • 32.
    RECURSION • We knowwe can call any function from anywhere inside another function • In the same way; we can call any function from inside that function. • This is known as Recursion. • This will create infinitely long execution • In order to prevent that, one who call has to specify an intelligent condition inside function
  • 33.
    FILES AND I/OMANAGEMENT How C Compiler Seek these things
  • 34.
    STARNDERD I/O DEVICES •STDIN -> Stranded Input Device : KEYBOARD • STDOUT -> Stranded Output Device : MONITOR
  • 35.
    I/O MANIPULATIONS. • CHARACTER •int getchar(void); • int putchar(char c); • STRING • char *gets(void); • int puts(char *s); • GENERAL • int scanf(const char *format); • int printf(const char *format); [%d, %c, %f, %s, %u, %x, %i,… ]
  • 36.
    FILE HANDLERs • FILE*fopen(const char *filename, const char *mode); a FUNCTION r Open file in read mode w Open empty file in write mode if file not exist: error a Open file with content in append mode if file not exist: error; append mode appends data to existing. r+ Open file in read/write mode mode w+ Open in write mode; if file not exist: create; a+ Open in append mode; if file not exist: create;
  • 37.
    FILE MANIPULATIONS. • CHARACTER •int fgetc (FILE *fp); • int fputc (int c, FILE *fp); • STRING • char *fgets(const char *s, int len, FILE *fp ); • int fputs(const char*c, FILE *fp); • GENERAL • int fscanf(FILE *fp, const char *format); • int fprintf(FILE *fp, const char *format);
  • 38.
    DYNAMIC MEMORY MANAGEMENT Efficiencyand Reliability depends on how Dynamic they are..
  • 39.
    Memory Allocations • Conceptof HEAP AND STACK Memory • void *calloc(int len, int size); • Allocates array of length<-len, and block of size<-size • Initialize location with 0; • void free(void *address) • Frees a piece of memory • void *malloc(int num*sizeof (datatype)) • Allocates an array of num bytes • void *realloc(void * address, int newsize) • Extends parent size
  • 40.
  • 41.
    Command Line arguments •It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code.
  • 42.
  • 43.
    POINTERS and VOID •Pointers are variables which stores address of another memory location. • Declaration : int *i; char* f; float* m[]; • Data Type Pointers define, which type of data is pointed by it. • Functions can also be pointed by it. • void *f; is the type which can hold any pointer; • Function pointers are pointers to the address of first line of function.
  • 44.
    POINT 2D Arrayusing Pointers • p[i][j] === *(*(p+i)+j));