Studentnotes C
Studentnotes C
2.2 .Non-Procedural Languages: This category also known as Problem Oriented languages. In this type of languages we can able to make program only at specific range like database. The followings are the examples of Non procedural languages e.g. - SQL etc
C Language:
Dennis Ritchie designed and implemented the first C compiler on a PDP-11. The C language was based on two languages: BCPL, written by Martin Richards, and B, written by Ken Thompson in 1970 for the first UNIX system on a PDP-7. The original ``official'' C language
2
was the ``K & R'' C, the nickname coming from the names of the two authors of the original ``The C Programming Language''. In 1988, the American National Standards Institute (ANSI) adopted a ``new and improved'' version of C, known today as ``ANSI C''. This is the version described in the current edition of ``The C Programming Language -- ANSI C''. Characteristics of C 1. C programs are efficient and fast because of variety of data types. 2. C is portable. 3. Ability to extend itself. 4. To develop Compilers. 5. For making Gaming Framework.
C Data Types:
Primary/Fundamental data types Derived data types User defined data types There are four fundamental data types in C. Data Type Character Integer Float Double char int float Double Syntax Type Alphabet Number Decimal Decimal Range -128 to 127 -32768 to 32767 3.4*10-38 to 3.4*1038 1.7e-308 to 1.7e+308 Size 1 Byte 2 Byte 4 Byte 8 Byte Access Specifier %c %d, %i %f %lf
Constants:
Constant is a value that cannot be changed during execution of the program. There are three types of constants-
Hexadecimal
Variable:
A variable (also called an object) is a place you can store a value. A declaration tells the compiler the name and type of a variable you'll be using in your program. In its simplest form, a declaration consists of the type, the name of the variable, and a terminating semicolon: char c; int i; float f; int i1, i2; Initialization of Variables:A declaration for a variable can also contain an initial value. int i = 1; int i1 = 10, i2 = 20; Variable Names- You can give your variables and functions any names you want . These names consist of letters, numbers, and underscores. Names must begin with a letter. The capitalization of names in C is significant: the variable names variable, Variable, and VARIABLE. Expressions: An expression is a combination of operators, constants, variables and function calls. The expression can be arithmetic, logical or relational. Some examplesx+y - arithmetic operations a>b - relational operators
4
a==b func(a,b)
Statements: A statement is an executable part of the program and causes the computer to carry out some action. These are categorized as1. Expression Statements ( x=5; x=y-z; ) 2. Compound Statements ( {int l=4,b=2; }) 3. Selection Statements (if, if..else, switch) 4. Iterative Statements (for, while, do..while) 5. Jump Statements (goto, continue, break, return) 6. Label Statements (case, default, label statement used in goto ) Comments: Comments are used for increasing readability of the program. There can be single line or multiple line comments // variable b represents basic salary (single line comment) /* this is a c program to calculate (multiple line comment) Simple interest*/
Basic Input-Output in C
6.1 Single Character Input/Output Functions:a) getchar()- Used to input single character. Syntax- varname=getchar();
Operators
Operator () [] -> . + [unary] - [unary] * [unary] & [unary] ++[prefix] ++[postfix] - - [prefix] - - [postfix]
sizeof()
Example
f() a[10] s->a s.a +a -a *a &a ++a a++ --a a sizeof(t1) a+b a-b a*b a/b a%b a<b a>b a <= b a >= b a == b a != b a&b a|b a^b ~a a >> b a << b a && b a || b !a a ? e1 : e2
Description/Meaning Function call Array reference Structure and union member selection Structure and union member selection Value of a Negative of a Reference to object at address a Address of a The value of a after increment The value of a before increment The value of a after decrement The value of a before decrement Size in bytes of object with type t1 a plus b a minus b a times b a divided by b Remainder of a/b 1 if a < b; 0 otherwise 1 if a > b; 0 otherwise 1 if a <= b; 0 otherwise 1 if a >= b; 0 otherwise 1 if a equal to b; 0 otherwise 1 if a not equal to b; 0 otherwise Bitwise AND of a and b Bitwise OR of a and b Bitwise XOR (exclusive OR) of a and b One's complement of a a, right-shifted b bits a, left-shifted b bits Logical AND of a and b (yields 0 or 1) Logical OR of a and b (yields 0 or 1) Logical NOT of a (yields 0 or 1) Expression e1 if a is nonzero; Expression e2 if a is zero
Operator
Unary Operators
+ [binary] - [binary] * [binary] /% < > <= >= == != & [binary] | ^ ~ >> << && || ! ?:
Arithmetic Operator
Relational Operators
Bitwise Operator
a, after b is assigned to it a plus b (assigned to a) a minus b (assigned to a) a times b (assigned to a) a divided by b (assigned to a) Remainder of a/b (assigned to a) a, right-shifted b bits (assigned to a) a, left-shifted b bits (assigned to a) a AND b (assigned to a) a OR b (assigned to a) a XOR b (assigned to a) e2 (e1 evaluated first)
Assignment Operators
Type Conversion:
Datatype of one operand is converted into datatype of another operand. This is known as type conversion. The different type of conversion are:
Implicit type Conversion: These conversions are done by the Compiler according to some predefined rules of C language. Explicit type Conversion or Type Casting: In these type of cases we can specify our own conversions known as type casting or coercion.
Control Statements
Statements are the ``steps'' of a program. By default, statements are executed in sequence, one after another. We can, however, modify that sequence by using control flow constructs which arrange that a statement or group of statements is executed only if some condition is true or false, or executed over and over again to form a loop. A statement is an element within a program which you can apply control flow to. C supports four types of control statements. 1. if..else 2. goto 3. switch 4. loop - while - dowhile - for A) Conditional/ Selection/ Decision Statements : used to execute the statements on basis of condition. 1. if Statements The simplest way to modify the control flow of a program is with an if statement. The syntax of an if statement is: if( expression ) statement where expression is any expression and statement is any statement. What if you have a series of statements that you enclose them in braces: if( expression ) { statement<sub>1</sub> statement<sub>2</sub> statement<sub>3</sub> } 2. if else Statements An if statement may also optionally contain a second statement, the ``else clause,'' which is to be executed if the condition is not met. The general syntax of an if else statement is : if( expression )
8
statement<sub>1</sub> else statement<sub>2</sub> It's also possible to nest one if statement inside another. if(expression) { if(expression) statement else statement } else { if(expression) statement else } statement
3. if else if Statements Used to check multiple conditions. Syntax: if(expression) { Statements; } else if(expression) { Statements; } else if(expression) { Statements; } else { Statements; } B) Loops Loops are the iterative constructs by which you repeat your code again and again. These are used when we want to execute a part of the program several times. There are three loop statements in C1. While Loop: A while loop has one control expression, and executes as long as that expression is true. The general syntax of a while loop is:
9
Initialization; while( condition ) { Statements; Increment/decrement; } A while loop starts out like an if statement: if the condition expressed by the expression is true, the statement is executed. However, after executing the statement, the condition is tested again, and if it's still true, the statement is executed again. As long as the condition remains true, the body of the loop is executed over and over again. 2. For Loops: The syntax of a for loop is for( initialization;condition;increment/decreement ) { Statements; } 3. dowhile Loops: The syntax of a do...while Loop is: do { .. ; Statements; Increement/decreement; } while (condition);
Nesting of Loops: When a loop is written inside the body of another loop, then it is
known as nesting of loops. Any type of loop can be nested inside any other type of loop. Syntax: for() { Statement; for() { Statement; .. } } Infinite Loops: The loops that go on executing infinitely and never terminate are called infinite loop. To come out of these loops break or goto statements are used. while(1) for(;;) do
10
{ .. . }
{ . .. }
{ . }while(1);
C) break statement: It is a Keyword used to exit from a switch or terminate a loop. When
break statement is encountered, loop is terminated and the control is transferred to the atatements immediately after the loop.
D) continue statement: It is a Keyword used when we want to go to the next iteration of the
loop after skipping some statements of the loop. Difference b/w break and continue: When break is encountered the loop terminates and the control is transferred to the next statement following the loop, but when a continue statement is encountered the loop is not terminated and the control is transferred to the beginning of the loop. E) goto: This is an unconditional control statement that transfers the flow of control to another part of the program.
F) switch case Statements It is a multi-way decision maker that tests the value of an expression against a list of integer or character. Syntax:switch(expression) { case value1: statement .. break; case value2: statement break; case value n: statement ..
11
default: statement . }
Functions
A function is a self-contained subprogram that is meant to do some specific, well-defined task.
1. 2.
Pre-defined Functions or Built-in Functions-These are the functions provided by the system. In C these are known as Library functions because they are provided by library. In that case we have to include header files in which these functions exist. User-define Functions- If you want to define your own functions then these are known as users define functions. Three things are important in user define function.
a.
Function Prototype or Declaration- The presence of the function prototype declaration lets the compiler know that we intend to call any particular function. The information in the prototype lets the compiler generate the correct code for calling the function, and also enables the compiler to check up on our code. Syntax- returntype function_name(datatype); Function Definition- What actions are to be taken whenever a function is called. A function must be defined outside any function. Syntax- returntype function_name(datatype arg1, datatye arg2, datatype arg n) { Statements; }
b.
c.
Function Calling- It near using function. There can be 2 tyoes of function calling. i. Which does not return a value Syntax- function_name (argname1, argname2.);
12
ii. Which return a value Syntax- varname= function_name (argname1, argname2.); Process of Execution for a Function Call A Function is an independent, reusable module of statements, that specified by a name. This module (sub program) can be called by its name to do a specific task. We can call the function, for any number of times and from anywhere in the program. The purpose of a function is to receive zero or more pieces of data, operate on them, and return at most one piece of data. A Called Function receives control from a Calling Function. When the called function completes its task, it returns control to the calling function. It may or may not return a value to the caller. The function main() is called by the operating system; main() calls other functions. When main() is complete, control returns to the operating system.
return statement: It is a keyword used in a function to return a value to the calling function. It
may also be used for immediate exit from the called function to the calling function without returning a value. This statement can appear anywhere inside the body of the function. There are two ways in which it can be usedreturn; return (expression);
Function Argument: The calling function sends some values to the called function for
communication; these values are called arguments or parameters.
Actual Arguments: The arguments which are mentioned in the function call are known as
actual arguments, these are the values which are actually sent to the called function. Eg. fun(x); Formal Arguments: The name of the arguments, which are mentioned in the function definition are called formal or dummy arguments. They are used just to hold the values that are sent by the calling function. Type of function Invoking2. With no argument and with no return value 3. With no argument and with return value 4. With argument and with no return value 5. With argument and with return value Passing Arguments in a Function OR Calling a function- A function can be called in 2 ways:
1.
Call by Value: - Whenever we call a function by value, actual argument will be copied on to the formal argument and if we change the value of formal argument then the value of actual argument will not be changed.
13
2.
Call by Reference- Whenever we call a function by reference the reference (address) of actual argument will be copy on formal argument instead of value thats why if we change the value of formal argument then the value of actual argument will be changed automatically.
Recursion: - It is the process of calling a function itself and such type of functions is known as recursive functions.
Arrays
An Array is a collection of one or more related variables of similar data type grouped under a single name. Or An array is a variable that can hold more than one value. We can represent the array a above with a picture like this: In C, arrays are zero-based: the ten elements of a 10-element array are numbered from 0 to 9. The subscript which specifies a single element of an array is simply an integer expression in square brackets. The first element of the array is a[0], the second element is a[1], etc. Array Declaration: Syntax: datatype arrayname[no of elements]; Array Initialization: I. At the time of Declaration: Syntax: II. Syntax: III. Syntax: datatype arrayname[no. of elements]={value1, value2,.., value n}; Element by Element: datatype arrayname[no. of elements]; arrayname[index value]=value; and so on.. From the User: scanf() is used to input value in an array.
Two Dimensional Arrays: If we give more than one dimensions at the time of Array declaration such type of Array is known as multidimensional Array.
14
If we are giving 2 dimension array is know as 2 dimensional Array. If we are giving 3 dimension array is know as 3 dimensional Array and so on. Array Declaration: Syntax: datatype arrayname[no of rows][no. of columns]; Memory Representation: 0 [0][0] [1][0] [2][0] No. of Columns 1 [0][1] [1][1] [2][1] 2 [0][2] [1][2] [2][2] No. of Rows 1 0 2
Array Initialization: I. Syntax: II. Syntax: III. Syntax: At the time of Declaration: datatype arrayname[no. of rows][no. of columns]={value1, value2,.., value n}; Element by Element: datatype arrayname[no. of rows][no. of columns]; arrayname[index value]=value; and so on From the User: scanf () is used to input value in an array.
1-D Arrays and Functions Passing Individual Array Elements to a Function: We can pass individual array
elements as arguments to a function like other simple variables. Passing whole 1-D Array to a Function:We can pass whole array as an actual argument to a function.
Default for local variables. (used with local variable) default for global variables (fast) Local variable stored in memory instead of RAM. Used to define global variables visible to all modules.
Used to classify variables that come into existence when a function is executed and are accessible as long as the function executes. Used when the program is executed & continues to be accessible as long as the entire program is running. Used to define local variables that should be stored in a CPU register instead of RAM. A variable can also be used outside a program file in which it is defined by declaring it with extern keyword
Pointers
Pointer variable A variable holds the address of another variable.
A pointer is a variable that points at, or refers to, another variable. That is, if we have a pointer variable of type ``pointer to int,`` it might point to the int variable i, or to the third cell of the int array a. Given a pointer variable, we can ask questions like, ``What's the value of the variable that this pointer points to?'' e.g. char option=Y; char *ptr=null; ptr=&option; *ptr=N;
Allots some memory location 4042 (for example) with a name option and stores value Y in it
Memory Address of variable
Value in option
Y
char option = Y;
option
option
4042
16
Creates a pointer variable with a name ptr Which can hold a Memory address Memory address of Variable option Is copied to the Pointer ptr
ptr = &option;
T h e a dv a n ta ge o f p o in te r a rra y is th a t th e le n g th o f e a c h ro w y m a y th e a rra in b e d iffe re n t. T h e im p o rta n t a p p lic a tio n o f p o in te r a rra re is h a ra c te r s trin g s to y c to s o f d iffe re n t le n g th . E x a m p le : c h a r *d a y[ ] = { u n d a , M o n d a, T u e s d a, W e d n e s d a yT h u rs d a, S y y y , y F rid a y, S a tu rd a }; y
*ptr = N;
a 25
4024
pa 4024
4056
ppa 4056
4078
base_ addre ss
void Pointer
void type pointer is a generic pointer, which can be assigned to any data type without cast during compilation or runtime. void pointer cannot be dereferenced unless it is cast.
int main( ) { void* p; int x = 7; float y = 23.5; p = &x; printf(x contains : %d\n, *( ( int *)p) ); p = &y; printf(y contains : %f\n, *( ( float *)p) ); } Output : x contains 7 y contains 23.500000
free ( p ); p = NULL; }
}; struct book b1 ; b1 *ptr ; ptr = (book *) calloc ( 10, sizeof ( book ) ); ptr = (book * ) realloc ( ptr , 35 * sizeof ( book ) ); Modifies the size of previously allocated memory to new size.
Pointer To Pointer:Pointer is a variable that can contain memory address. This pointer
variable takes some space in memory and hence it is also has an address. We can store the address of a pointer variable in some other variable., which is known as pointer to pointer variable. Syntax of declaring a pointer to pointer is asdata_type **pptr;
19
Strings
A String is sequence of characters. In C strings are implemented by an array of characters terminated with a null character \0 (back slash followed by zero). char name[] = Ravi Kiran; OR char name[]={R,a,v,i,,K,i,r,a,n,\0}; R a v i K i r a n \0
name
name is an array of characters has size of eleven characters including a null character \0(ascii code is zero). char name[25] ; scanf(%s, name); /*reading a string until a white space is encountered ( & operator is not required )*/ printf(%s, name); /*printing a string in input window */ gets(name) ; /* reading a string including white spaces until \n is encountered. */ puts(name); /* printing a string and moves cursor to new line */ String Manipulation Functions in <string.h> strlen(s1) strcpy(s1,s2) strcat(s1,s2) strcmp(s1,s2) - returns the length of string excluding the last null character. - copies characters in s2 into s1. - concatenates s2 to s1. -compares s1 with s2 lexicographically and returns 0 if two strings are same , returns -1 if s1 is before s2 and returns +1 if s1 is after s2.
strcmpi(s1,s2) -compares s1 with s2 like strcmp() but case of characters is ignored. strchr(s1,ch) strstr(s1,s2) -returns pointer to first occurrence of the character ch in s1. -returns pointer to first occurrence s2 in s1.
20
strrev(s1)
String Pointers: We can take a char pointer and initialize it with a string constant. For eg.
char *ptr=Chennai;
Dr e eiv d Tp s ye
F nt n u cio Tp ye
Ar y y e r a Tp
P ine o tr Tp ye
Sr cue t ut r Tp ye
U io T p n n ye
Array Collection of one or more related variables of similar data type grouped under a single name. Structure Collection of one or more related variables of different data types, grouped under a single name. Use of Structures:Structures help to store related data together and are identified by a single name. These structures can also be treated as user-defined data types. A structure can
21
include different data types or arrays as its members. Structures can be used to create complex data structures like linked list, stack or queue which can be implemented to perform larger and more complex operations.
STR C R U TU E -B O O K Structure tag
struct
book { int book_id ; char title[50] ; char author[40] ; int pages ; float price ;
struct < structure_tag_nam > e { data type < m ber 1 > em data type < m ber 2 > em . . . . data type < m ber N > em };
};
Union - A union is a structure all of whose members share the same memory.
It is a variable, which is similar to the structure and contains number of members like structure. In the structure each member has its own memory location whereas, members of union share the same memory. The amount of storage allocated to a union is sufficient to hold its largest member.
struct student { int rollno; float avg ; char grade ; }; union pupil { int rollno; float avg ; char grade; }; int main() { struct student s1 ; union pupil p1; printf ( %d bytes , sizeof ( struct student ) ) ; printf ( %d bytes , sizeof ( union pupil ) ) ; } Output : 7 bytes 4 bytes
grade
22
M oryallottedtounionpupil em
Address 5000 5001 5002 5003
File Handling
Introduction- The idea of storing the information has laid down the concept of file handling. A file is a bunch of bytes stored on some storage devices like hard disk, floppy disk etc. Most of the application programs process large volume of data which is permanently stored in files. We can write program that can read data from file(s) and write data to file(s). Data transfer is generally done in two ways: i. Reading data from Input device (memory) and writing into file(s). ii. Reading data from file(s) and writing into or display on Output device(memory).
v) Correctness of data the contents of a data file are verified and the errors, if any, can be removed.
Types of Data files TEXT FILE and BINARY FILE Text Files: It contains alphanumeric datainput using a text editor program. ASCII file format is
used, so it can be displayed on screen or manipulated easily (Less Data Security) . Data translation is required, resulting in slower speed.
Binary File: It allows us to write alphanumeric data to the disk file in less number of files as
compared to text files. The data is stored in Binary (Machine) language, not readable without program code, data is secure as no easy manipulation is there. Speed is faster as data needs no translation.
3. searching for required data from file a binary file is opened in input mode for searching data. The file can be read sequentially one by one each record or randomly by going to that particular location. 4. Appending data to a file appending means addition of new records to an already existing file. 5. Insertion of data in sorted file 6. Deletion of data 7. Modification/Updation of data
Opening a File:
Declaration: Example: FILE *fopen(const char *filename, const char *mode); FILE *fp1, *fp2; fp1=fopen(myfile.txt,w); fp2=fopen(yourfile.dat,r);
The possible values of mode are r - open a file in read-mode, set the pointer to the beginning of the file. w - open a file in write-mode, set the pointer to the beginning of the file. a - open a file in write-mode, set the pointer to the end of the file. r+ - open a file in read/write-mode, if the file does not exist, it will not be created. w+ - open a file in read/write-mode, set the pointer to the beginning of the file. a+ - open a file in read/append mode. wb- Binary file opened in write mode ab+ - Binary file opened in append mode rt+ - Text file opened in update mode w Text file opened in write mode
Closing a File:
Declaration: int fclose (FILE *fptr); We can also close multiple files by calling a single function fcloseall(). Declaration: int fcloseall (void);
25
End Of File: The file reading functions need to know the end of file so that they can stop
reading. When the end of file is reached, the operating system sends an end-of-file signal to the program.
The functions used for file I/O are Character I/O - fgetc(), fputc(), getc(), putc() String I/O - fgets(), fputs() Integer I/O - getw(), putw() Formatted I/O - fscanf(), fprintf() Record I/O - fread(), fwrite()
Character I/O
A number of functions provide for character oriented I/O. Their declarations are:
#include <stdio.h> /* character input */ int fgetc(FILE *stream); int getc(FILE *stream); int getchar(void); int ungetc(int c, FILE *stream); /* character output */ int fputc(int c, FILE *stream); int putc(int c, FILE *stream); int putchar(int c); /* string input */ char *fgets(char *s, int n, FILE *stream); char *gets(char *s);
26
/* string output */ int fputs(const char *s, FILE *stream); int puts(const char *s);
Integer I/O
The getw and putw functions: These are integer-oriented functions. They are similar to get c and putc functions and are used to read and write integer values. These functions would be usefull when we deal with only integer data. The general forms of getw and putw are:
/*Example program for using getw and putw functions*/ #include< stdio.h > main() { FILE *f1,*f2,*f3; int number I; printf(Contents of the data filenn); f1=fopen(DATA,W); for(I=1;I< 30;I++) { scanf(%d,&number); if(number==-1) break; putw(number,f1); } fclose(f1); f1=fopen(DATA,r); f2=fopen(ODD,w); f3=fopen(EVEN,w); while((number=getw(f1))!=EOF)/* Read from data file*/ { if(number%2==0) putw(number,f3);/*Write to even file*/ else putw(number,f2);/*write to odd file*/ } fclose(f1); fclose(f2); fclose(f3); f2=fopen(ODD,r); f3=fopen(EVEN,r); printf(nnContents of the odd filenn); while(number=getw(f2))!=EOF) printf(%d%d,number); printf(nnContents of the even file); while(number=getw(f3))!=EOF) printf(%d,number); fclose(f2); fclose(f3); }
String I/O
27
fputs(): This function writes the null terminated string pointed to by str to a file. Declaration: int fputs(const char *str, FILE *fptr); fgets(): This function is used to read characters from a file and these characters are stored in the string pointed to by str. Declaration: char *fgets( char *str, int n, FILE *fptr);
Formatted I/O
fprintf(): This function is same as the printf() but it writes formatted data into files instead of the standard output. Declaration: fprintf( FILE *fptr, const char *format [, argument, ]); fscanf(): This function is similar to the scanf() but it reads data from file instead of standard input. Declaration: fscanf( FILE *fptr, const char *format [, address, ]);
0 1 2
2. ftell(): This function returns the current position of the file position pointer. The value is counted from the beginning of the file. Declaration: long ftell( FILE *fptr);
29