Post on 17-Jan-2018
description
transcript
Fundamentals and History of C
C is developed by Dennis RitchieC is a structured programming languageC supports functions that enables easy
maintainability of code, by breaking large file into smaller modules
Comments in C provides easy readabilityC is a powerful language
PROGRAM STRCTURE IN C
#include<stdio.h>#include<conio.h>void main(){
--other statements}
HEADER FILESThe files that are specified in the include
section is called as header fileThese are precompiled files that has some
functions defined in themWe can call those functions in our program
by supplying parametersHeader file is given an extension .hC Source file is given an extension .c
MAIN FUNCTIONThis is the entry point of a programWhen a file is executed, the start point is the
main functionFrom main function the flow goes as per the
programmers choice.There may or may not be other functions
written by user in a programMain function is compulsory for any c
program
Sample program#include<stdio.h>#include<conio.h>int main(){
printf(“Hello”);return 0;
} This program prints Hello on the screen
when we execute it
HOW TO RUN C PROGRAM Type a programSave itCompile the program – This will generate an
exe file (executable)Run the program (Actually the exe created out
of compilation will run and not the .c file)In different compiler we have different option
for compiling and running. We give only the concepts.
Points to rememberCase Sensitive • Case matters in C. A is not a• Add plenty of comments (/* */ or //)• Good layout, not: main() {printf("Hello World\n");}• Use meaningful variable names• Initialize your variables• Use parentheses to avoid confusion:a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0
DATA TYPESPrimitive data types
int, float, double, charAggregate data types
Arrays come under this categoryArrays can contain collection of int or float or
char or double dataUser defined data types
Structures and enum fall under this category.
VARIABLESVariables are data that will keep on changingDeclaration
<<Data type>> <<variable name>>;int a;
Definition<<varname>>=<<value>>;a=10;
Usage<<varname>>a=a+1; //increments the value of a by 1
RULES FOR VARIBLE NAMEShould not be a reserved word like int etc..Should start with a letter or an underscore(_)Can contain letters, numbers or underscore. No other special characters are allowed
including spaceVariable names are case sensitive
A and a are different.
INPUT & OUTPUTInput
scanf(“%d”,&a);Gets an integer value from the user and stores
it under the name “a”Output
printf(“%d”,a)Prints the value present in variable a on the
screen
OPERATORSArithmetic (+,-,*,/,%)Relational (<,>,<=,>=,==,!=)Logical (&&,||,!)Bitwise (&,|)Assignment (=)Compound assignment(+=,*=,-=,/=,%=,&=,|
=)Shift (right shift >>, left shift <<)
OPERATORS(Contd.)
Increment and Decrement Operators ++ Increment operator
-- Decrement Operator k++ or k-- (Post-increment/decrement) k = 5;x = k++; // sets x to 5, then increments k to 6
(contd.)
++k or --k (Pre-increment/decrement)k = 5;x = ++k; // increments k to 6 and then sets to
the resulting value, i.e., to 6
CONTROL CONSTRUCTS
Conditional Statementsif (condition) {
stmt 1; //Executes if Condition is true}else{
stmt 2; //Executes if condition is false}
SWITCH & BREAKswitch(var){case 1: //if var=1 this case executes
stmt;break;
case 2: //if var=2 this case executesstmt;break;
default: //if var is something else this will executestmt;
}
LOOPS
FOR LOOPThe syntax of for loop is
for(initialisation;condition checking;increment){
set of statements}Eg: Program to print Hello 10 timesfor(I=0;I<10;I++){
printf(“Hello”);}
WHILE LOOPThe syntax for while loop
while(condn){
statements;}
Eg:a=10;while(a != 0) Output: 10987654321{
printf(“%d”,a);a- -;
}
DO WHILE LOOPThe syntax of do while loop
do{
set of statements}while(condn);
Eg:i=10; Output:do 10987654321{
printf(“%d”,i);i--;
}while(i!=0)
ARRAYS
ARRAYS
Arrays are collection of data that belong to similar data type
Arrays are collection of homogeneous dataArray elements can be accessed by its
position in the array called as index
Contd.Array index starts with zeroThe last index in an array is num – 1 where num
is the no of elements in a arrayint a[5] is an array that stores 5 integersa[0] is the first element where as a[4] is the fifth
elementWe can also have arrays with more than one
dimensionfloat a[5][5] is a two dimensional array. It can
store 5x5 = 25 floating point numbersThe bounds are a[0][0] to a[4][4]
String functionsstrlen(str) – To find length of string strstrrev(str) – Reverses the string str as rtsstrcat(str1,str2) – Appends str2 to str1 and
returns str1strcpy(st1,st2) – copies the content of st2 to
st1strcmp(s1,s2) – Compares the two string s1
and s2strcmpi(s1,s2) – Case insensitive comparison
of strings
Function Syntax of functionDeclaration section<<Returntype>> funname(parameter list);Definition section<<Returntype>> funname(parameter list){
body of the function}Function CallFunname(parameter);
Example#include<stdio.h>void fun(int a); //declarationint main(){
fun(10); //Call}void fun(int x) //definition{
printf(“%d”,x);}
ACTUAL & FORMAL PARAMETERS
Actual parameters are those that are used during a function call
Formal parameters are those that are used in function definition and function declaration
Call by valueCalling a function with parameters passed as
values
int a=10; void fun(int a)fun(a); {
defn;}
Here fun(a) is a call by value.Any modification done with in the function is local
to it and will not be effected outside the function
Call By ReferenceCalling a function by passing pointers as
parameters (address of variables is passed instead of variables)
int a=1; void fun(int *x)fun(&a); {
defn;}
Any modification done to variable a will effect outside the function also
Explanation
a and x are referring to same location. So value will be over written.
Explanation
ConclusionCall by value => copying value of variable in
another variable. So any change made in the copy will not affect the original location.
Call by reference => Creating link for the parameter to the original location. Since the address is same, changes to the parameter will refer to original location and the value will be over written.
StructuresStructures are user defined data typesIt is a collection of heterogeneous dataIt can have integer, float, double or character
data in itWe can also have array of structuresstruct <<structname>>{
members;}element;We can access element.members;
Examplestruct Person{int id;char name[5];}P1;P1.id = 1;P1.name = “vasu”;
typedef statementUser Defined Data Types The C language provides a facility called typedef
for creating synonyms for previously defined data type names. For example, the declaration:
typedef int Length; makes the name Length a synonym (or alias) for
the data type int.
(contd.)The data “type” name Length can now be
used in declarations in exactly the same way that the data type int can be used:
Length a, b, len ; Length numbers[10] ;
UNION
UNIONUnion has members of different data types,
but can hold data of only one member at a time.
The different members share the same memory location.
The total memory allocated to the union is equal to the maximum size of the member.
EXAMPLE#include <stdio.h>
union marks{ float percent; char grade;};int main ( ){ union marks student1; student1.percent = 98.5; printf( "Marks are %f address is %16lu\n", student1.percent, &student1.percent); student1.grade = 'A'; printf( "Grade is %c address is %16lu\n", student1.grade, &student1.grade);}
ENUM
(ENUMERATED DATA TYPE) Enumeration is a user-defined data type.
It is defined using the keyword enum and the syntax is:
enum tag_name {name_0, …, name_n} ;
The tag_name is not used directly. The names in the braces are symbolic constants that take on integer values from zero through n.
(contd.) As an example, the statement: enum colors { red, yellow, green } ; creates three constants. red is assigned the value 0, yellow is assigned 1 and green is assigned 2.
POINTERPointer is a special variable that stores
address of another variableAddresses are integers. Hence pointer stores
integer dataSize of pointer = size of intPointer that stores address of integer
variable is called as integer pointer and is declared as int *ip;
Pointers(Contd.)Pointers that store address of a double, char
and float are called as double pointer, character pointer and float pointer respectively.
char *cpfloat *fpdouble *dp;Assigning value to a pointer
int *ip = &a; //a is an int already declared
Exampleint a;a=10; //a stores 10int *ip;ip = &a; //ip stores address of a (say 1000)
ip : fetches 1000*ip : fetches 10* Is called as dereferencing operator
Dynamic Memory Allocation
The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this functions, which can be used to allocate and free memory during the program execution.
malloc()A block mf memory may be allocated using
the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form:
ptr=(cast-type*)malloc(byte-size);
ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size.
Example: x=(int*)malloc(100*sizeof(int));
Contd…..
On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int
CallocCalloc is another memory allocation function
that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is:
ptr=(cast-type*) calloc(n,elem-size);
Contd……The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.
free()Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required.free(ptr); ptr is a pointer that has been created by using malloc or calloc
realloc The memory allocated by using calloc or
malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is :
ptr=realloc(ptr,newsize);
FILE HANDLING
IntroductionFiles are places where data can be stored
permanently.Some programs expect the same set of data
to be fed as input every time it is run.Cumbersome.Better if the data are kept in a file, and the
program reads from the file.Programs generating large volumes of
output.Difficult to view on the screen.Better to store them in a file for later viewing/
processing
Basic File OperationsOpening a fileReading data from a fileWriting data to a fileClosing a file
Opening a FileA file must be “opened” before it can be used.
FILE *fp; : fp = fopen (filename, mode);fp is declared as a pointer to the data type FILE.filename is a string - specifies the name of the
file.fopen returns a pointer to the file which is used
in all subsequent file operations. mode is a string which specifies the purpose of
opening the file:“r” :: open the file for reading only “w” :: open the file for writing only“a” :: open the file for appending data to it
Closing a FileAfter all operations on a file have been
completed, it must be closed.Ensures that all file data stored in memory
buffers are properly written to the file.General format: fclose (file_pointer) ;
FILE *xyz ; xyz = fopen (“test”, “w”) ; ……. fclose (xyz) ;
Read/Write Operations on Files
The simplest file input-output (I/O) function are getc and putc.
getc is used to read a character from a file and return it.
char ch; FILE *fp;…..ch = getc (fp) ;
getc will return an end-of-file marker EOF, when the end of the file has been reached.
putc is used to write a character to a file.char ch; FILE *fp;……putc (c, fp) ;
main() { FILE *in, *out ; char c ;
in = fopen (“infile.dat”, “r”) ; out = fopen (“outfile.dat”, “w”) ; while ((c = getc (in)) != EOF) putc (toupper (c), out); fclose (in) ; fclose (out) ;}
Contd.We can also use the file versions of scanf and
printf, called fscanf and fprintf.General format:
fscanf (file_pointer, control_string, list) ; fprintf (file_pointer, control_string, list) ;
Examples:fscanf (fp, “%d %s %f”, &roll, dept_code, &cgpa) ;fprintf (out, “\nThe result is: %d”, xyz) ;
Command line argumentCommand line arguments are parameters supplied
to a program, when the program is invoked.
How do these parameters get into the program?Every C program has a main function.main can take two arguments conventionally called argc
and argv. Information regarding command line arguments are
passed to the program through argc and argv.
INTRODUCTION TO C PREPROCESSOR
C PreprocessorOverviewPreprocessor DirectivesConditional Compilation
Overview Six phases to execute C:
1. Edit2. Preprocess3. Compile4. Link5. Load6. Execute
C PreprocessorAll preprocessor directives begin with #Possible actions
Inclusion of other filesDefinition of symbolic constants & macrosConditional compilation of program codeConditional compilation of preprocessor
directives
Preprocessor Directives #define for symbolic constants
#define identifier text Creates symbolic constants The “identifier” is replaced by “text” in the
programExample#define PI 3.14area = PI * radius * radius; Replaced by “area = 3.14 * radius * radius” by
preprocessor before compilation
Conditional Compilation Controls the execution of preprocessor
directives & compilation of codeDefine NULL, if it hasn’t been defined yet#if !defined(NULL)#define NULL 0
#endifUse to comment out code (for comments)#if 0code prevented from compiling
#endif
THANKS