my c notes

41
13.09.2008 Introduction to C BCPL – Basic Combined Programming Language – Martin Richard B Language – Ken Thompson C Language – Denis Ritchie C++ Bjarne Stroustrup Java James Gosling C# from Microsoft Features of C C is a high level language with the capabilities of middle level language. C is a format free language C is portable C is a structured or modular programming language Every C program must have .c extension Every executable C program must have a main() function followed by pair of braces main() function can have any of six syntaxes o void main() o int main() o void main(int argc, char *argv[]) o int main(int argc, char *argv[]) o void main(int argc, char *argv[], **ppenv) o int main(int argc, char *argv[], **ppenv) Every statement must terminate by a semicolon ; C provides a big set of library functions under special files called as header files with .h extension o stdio.h printf(),fprintf(), scanf(), gets(), fflush(), NULL, stdin, stdout, strprn etc. o conio.h clrscr(), gotoxy(), getch(), getche() etc. o math.h pow(), log(), cos(), atoi(), atof() etc. o ctype.h toupper(), tolower(), isdigit(), isalpha(), isupper(), islower() etc. o string.h

Upload: brijendra-mohan-gupta

Post on 12-Nov-2014

936 views

Category:

Documents


2 download

DESCRIPTION

it is my B.P.Sharma C notes

TRANSCRIPT

Page 1: my c notes

13.09.2008

Introduction to C

BCPL – Basic Combined Programming Language – Martin RichardB Language – Ken ThompsonC Language – Denis Ritchie

C++ Bjarne StroustrupJava James GoslingC# from Microsoft

Features of C

C is a high level language with the capabilities of middle level language. C is a format free language C is portable C is a structured or modular programming language Every C program must have .c extension Every executable C program must have a main() function followed by pair of

braces main() function can have any of six syntaxes

o void main()o int main()o void main(int argc, char *argv[])o int main(int argc, char *argv[])o void main(int argc, char *argv[], **ppenv)o int main(int argc, char *argv[], **ppenv)

Every statement must terminate by a semicolon ; C provides a big set of library functions under special files called as header files

with .h extensiono stdio.h

printf(),fprintf(), scanf(), gets(), fflush(), NULL, stdin, stdout, strprn etc.

o conio.h clrscr(), gotoxy(), getch(), getche() etc.

o math.h pow(), log(), cos(), atoi(), atof() etc.

o ctype.h toupper(), tolower(), isdigit(), isalpha(), isupper(), islower() etc.

o string.h strlen(), strcpy(), strrev(), strcat(), strcmp() etc.

To include a header file use any of two methodso #include <headerfile>o #include “header file”

#include is called as pre-processor directive Add some remarks or comment inside the programs for future use

o Use /* and */ delimiters to use the comments

Page 2: my c notes

Software Requirements

TC 3.0TC 4.5Borland C++ 5.0

Installing TC 3.0

TURBOC –d c:\

Creates a TC folder. Double click on TC.EXE file under TC\BIN folder

Turbo C is an IDE (Integrated Development Environment) from Turbo company overtaken by Borland.

Key combinations used with TC

Alt+X Exit TC Ctrl+F1 Context Sensitive Help F2 Save F3 Open Alt+F3 Close Window Alt+Window number – to switch between the windows F5 -> Full Screen or Restore window Alt+F5 To see output window

14.09.2008

Block Operations

Selection Shift+Arrow keysCopy Ctrl+KCMove Ctrl+KVDelete Ctrl+KYDe-select Ctrl+KHDelete a line -> Ctrl+YUndo Alt+Backspace

Basic functionsprintf(“message”); to print on screen in black/whitecprintf(“message”); to print on screen in defined colortextcolor(colorname); to define a text colortextbackground(colorname); to define a text backgroundgotoxy(column,row); to send cursor to given positionclrscr(); clear the screen

Compilations options

Page 3: my c notes

Alt+F9 CompileF9 BuildCtrl+F9 Build and Run

.c tcc .obj (Pass 1) + .LIB Tlink exe (Pass2)

Files in C

.c Source File

.obj Object File

.exe Executable file

.bak Backup file

Data Types- Special keywords that define the type of data and amount of data

Types of data types Primary Data Types

o char – 1 byteo int – 2 or 4 byteso float – 4 bytes – 6 dec.placeso double – 8 bytes- 14 dec. placeso void - nothing

Modified Data Typeso Data types created by modifying the primary types using some special

keywords called modifiers short long signed unsigned

o char signed char (char) unsigned char

o int short int (short)– 2 bytes unsigned short int – 2 byte long int (long) – 4 byte unsigned long int unsigned int

o double long double – 10 bytes

Derived data typeso Created using primary and modified typeso Also called as custom typeso Arrays, Pointers, Structures, Unions, Bitfilds etc.

Communicating data with outside world and memory

Page 4: my c notes

- Use the special codes called format specifiers

%d - decimal%o - Octal%x or %X – Hexa Decimal%i - integer%c - Characters%s - String without space%[^\n] – String with space%ld - long%u - unsigned int%lud - unsigned long int%f - fixed float%e - scientific float%g - general float%lf - double and long double

Memory Variables

- A name given to some memory location to store and retrieve the data- A variable name must associate a data type

<datatype> <variablename>;

Example

int empid;char gender;float basic;char name[51];

Variable Naming Rules

- A variable name can have alphabets (a-z, A-Z), digits (0-9) or underscore (_) only- Can never start with digit- Keywords cannot be used a variable names- A variable can be upto any length but first 32 characters are significant

Literals

- The values that we use from our side in variable assignments, expression etc.

Page 5: my c notes

Types of Literals1. Integral Literals

a. Default is intb. int n=56;c. long k=45L;d. usigned int p=45U;e. Use l or L for long and u or U for unsigned

2. Floating literalsa. Default is doubleb. Use f or F for floatsc. double k=1.1;d. float p=1.1F;

3. Character Literalsa. Characters are enclosed in single quotesb. Each character takes one bytec. Characters and numbers are interchangeablechar ch=’A’;orchar ch=65;

d. C provides some special characters made of two or more characters but represent only one character. Used with \

i. \\ - print the \ii. \’ – single quotes

iii. \” – double quotesiv. \0 – Null Characterv. \t – Horizontal Tab

vi. \n – New Linevii. \r – Carriage Return

viii. \a or \007 – alert or beep sound

ExamplePrint the following line

He said, “\n” is made for new line.

4. Sting literalsa. Enclosed in double quotesb. Each string is terminated by null character \0

char name[]=”Vikas”; //6char name[40]=”Vikas”;//40

char name[40];name=”Vikas”; //error

Note: use sizeof() operator to see the size of a variable or data type

Next Topics

Page 6: my c notes

Input Methodsscanf()getch()getche()getchar()gets()

fflush()

OperatorsConditional StatementsLooping Statements

20.09.2008

Input Methods

scanf() – to read any kind of data using specifier along with address of variable- Use & operator to get address of some variable

Syntaxscanf(“specififer”,address of variable);

%d or %i decimal%c character%s string without space%[^\n] string with space%f float%lf double and double %u unsigned%lud unsigned long int

For Character Inputgetch() – Get a character but don’t echo it. Un-buffered modegetche() – Get a character and echo it. Un-buffered Modegetchar() – Get a character. Buffered Mode

For String inputgets(stringvariable) – to get a string including space

Page 7: my c notes

Operators

Arithmetic operators+ - * / %5/2 25.0/2 2.55.0/2.0 2.55/2.0 2.5

Cast Operator- To covert one kind of data to another kind using casting

int a=5,b=2;float c=a/b; 2.0float c=(float)a/b; 2.5 cast operator

Relational or conditional or comparison operators- Used to compare two values- There are six operators

o == Equals to operatoro != Not equals to operatoro >o >=o <o <=

- Returns 1 for true and 0 for false

int n=5>0; //1int k=5<0; //0

Logical operators- Combine two conditions or negate the result of a condition

o && Logical Ando || Logical Oro ! Logical Not

- && returns true if both the conditions are true- || returns true if any one of the conditions is true- In case of &&, if first condition is false the second will not be checked- If case of ||, if the first condition is true then second will be not be checked- All values other than 0 are counted as true

Problemint n= 67 && printf(“Hello”);printf(“%d”,n);

OutputHello1

Page 8: my c notes

Problemint n= 3 || printf(“Hello”);printf(“%d”,n);

Output1

Bitwise operators- The operators that operate on bits are called as bit operators

o & Bitwise Ando | Bitwise Oro ^ Bitwise XORo << Left Shifto >> Right Shift

int n=6 & 9; //0

0011001001-------00000-------

int k=67 | 34; //9964 32 16 8 4 2 11 0 0 0 0 1 10 1 0 0 0 1 0--------------------------------------------------------1 1 0 0 0 0 1-------------------------------------------------------

int k=67 ^ 34; //97

int k=5<<2; //2064 32 16 8 4 2 10 0 0 0 1 0 10 0 0 1 0 1 0 (first move)0 0 1 0 1 0 0 (second move)

Assignment operators= n=5;+= n=n+5; n+=5;-=*=/=++ one increment n=n+1; n++ or ++n-- one decrement n=n-1; n-- or --n;

Post increments- First use the current value then increment it

Page 9: my c notes

int n=6;int k= n++ + 7; //6+7 13

Pre increments- First increment the value then use itint n=6;int k= ++n + 7; //7+7 14

Questions1. Differentiate between = and ==2. Differentiate between ‘A’ and “A”3. Different between & and &&4. Different between | and ||

Note: Bitwise operator can be used like logical operator but they always checks both the conditions

int n=78 & printf(“Hello”);printf(“%d”,n);

OutputHello4

64 32 16 8 4 2 11 0 0 1 1 1 00 0 0 0 1 0 1--------------------------------------------------------0 0 0 0 1 0 0--------------------------------------------------------

Conditional Statements

- Special statements used for decision making process- C provides two statements and one operator for condition making

1. if statement2. switch statement3. ternary operator (?:) – having three operands

if statements- It has multiple syntaxes

[A]if(condition)

statement;

[B]if(condition){

Page 10: my c notes

Statements;}

[C]if(condition)

statement;else

statement;[D] Nested if (condition within condition)

if(condition){

if(condition){

Statements;}

}[E] If-else ladder

if(condition)statement;

else if(condition)statement

else if(condtion)statement;

elsestatement;

27.09.2008

Difference between literal and constant

- Literals are the values used directly without user input- Constant is a like of variable or Macro whose value once assigned cannot be

modified

#define n 10

n=11; //Error

ORconst int n=5;

Page 11: my c notes

Ternary operator (?:)- Shortcut to if-else

Condition ? true part : false part;

Exampleint g=a>b?a:b;int g=a>b? (a>c?a:c) : (b>c?b:c);

Switch Statement

- Used only for equality comparisons

switch(variable){

case value1: statements; break;case value2: statements;break;…default:statements;

}

Example

1. Get a digit and print into words.2. Get a character and check it to be vowel or consonant

Looping Statements- Repetition of same statements again and again till the condition is true- C provides thee kinds of loops

o whileo do-whileo for

- while is called as pre-check loopo It first checks the conditions, if the condition is true then statements get

executed

initilization;while(condition){

Statements;Updation;

}- for loop is very similar to while loop

for(initialization;condition;updation)statement;

orfor(initialization;condition;updation)

Page 12: my c notes

{statements;

}

Do-while loop- A post-check loop that executes at least once irrespective of condition

do{

Statements;Updation;

}while(condition);

28.09.2008

1. View the ASCII characters and their codes.2. Print on the screen

a. α + β = δ (224, 225, 235)b. printf(“%c + %c = %c”,224, 225, 235);

3. Print heart symbols in third line4. Print the whole screen with hearts5. Print the following for given number of lines

1223334444

1121231234

ABBCCCDDDD

AABABCABCD

ExplanationTotal lines nLine no. from 1 to n l (dependency on n)Characters per lines 1 to l i (dependency on l)

6. Print the following based on user input

Page 13: my c notes

* ********

1 12112321 121 1

Class assignment

Write a program to get a number and print it into words678 Six Seven Eight10 Minutes

Reverse the number Crack the digits of the reversed number Print the word corresponding to digit

Get a number and check to be palindrome.

Get a number and check it to be prime.

Get two numbers from keyboards and print all prime numbers in range (inclusive)

04.10.2008

Working with Arrays- Array is a variable that can hold multiple data elements of similar type- Each element is differentiated by a number called Index Number- Index number starts with 0- Types of arrays

o Single Dimension Array Having only one row

o Two Dimensional Array Having multiple rows

o Multi-Dimensional Having more than 2 dimensions

Creating Single Dimensional ArraySyntax

<datatype> <arrayname>[size];

Exampleint n[5]; //n[0] to n[4]

double num[4]; //num[0] to num[3]

Double Dimensional Array

Page 14: my c notes

- Having rows and columnso int n[3][4]; // 3 rows and 4 columns 12 elements

Array Initialization- Provide values while creating an array

int n[]={4,6,1,9}; 4 elementsint n[10]={3,4,6,2,4};

Sample Case- Get 5 numbers and print average of it- Get 5 numbers and print greatest of those numbers- Get any number of numbers and print greatest of it- Create an array of 3 X 4 and input the values in that array. Show the values of

array in proper matrix format

05.10.2008

Matrix Multiplication

- Columns in first matrix must be equal to rows in second column

A[i][j] X B[j][k] A[i][k]

for(i for(k {

C[i][k]=0 for(j

C[i][k]+=A[i][j]*B[j][k]; }

String Operations

1. Get a string and print the length of the string2. Reverse print a string3. Swapping or interchanging of numbers

a. Method 1i. Using Third variable

1. int a=5,b=10,temp;2. temp=a;3. a=b;4. b=temp;

b. Method 2i. Without using third variable

1. int a=5,b=10;2. a=a+b;

Page 15: my c notes

3. b=a-b;4. a=a-b;

c. Using XOR operator ^i. a^=b;

ii. b^=a;iii. a^=b;

d. Using XOR in one linei. a^=b^=a^=b;

11.10.2008

Number Sorting

- Get a numbers, compare and swap them for sorting

Functions

- A block of statements given a name to do some specific repetitive task- Functions are of two types

o Library Functions Provided under header files

o User Defined Functions (UDF) Created by programmers for their needs

- Library functionso math.h

pow(n,p) abs(n) log() cos() tan() atoi() – String to integer conversion atof() – String to float conversion

char data[]=”345.44”; float x=atof(data);

o ctype.h Characters related operations

toupper() tolower() isupper() islower() isalpha() isdigit()

Get a string from print in toggle case Amit aMIT

Get a string and count lower, upper and special characterso string.h

For string operations strupr(str) – To upper case string strlwr(str) – To lower case string strrev(str) – To reverse the string strlen(str) – String length

Page 16: my c notes

strcmp(s1,s2) To compare two stringso Returns 0 if s1==s2o Returns >0 if s1>s2o Returns <0 if s1<s2

strcpy(target, source) – To copy string from source to target strcat(s1,s2) To concatenate two strings

12.10.2008Creating User Defined Functions

- A function has three segmentso Function Declarationo Function Definitiono Function Call

Function Declaration gives the function name, number of arguments, type of arguments and return type. Function can be categorized in two categories depending on return type called as void functions or non-void functions.

- It is declared above main()

void drawline(int, int, int);ORvoid drawline(int x, int y, int count);

int mylen(char str[]);

long factorial(int);

Function Definition provides the real programming logic. It can be written below the main() or above the main(). If the function definition is provided above() method then declaration is not required.

<returntype> functionname(<argumentlist>){

Statements;[return variable];

}

void drawline(int x, int y, int num){

int i;gotoxy(y,x); for(i=1;i<=num;i++) printf(“-“);

}

Test Program

Page 17: my c notes

Get a number and print in Indian Numeral Style

56789 Fifty Six Thousand Seven Hundred Eighty Nine

NextRecursionPassing values to the functionsPointersCommand Line Arguments

19.10.2008

Recursion- A function that calls itself within it is called as recursive function and the process

is called as recursion- Examples

o Factorial of Numberso Pascal Triangleo Fibonacci Serieso Tower of Hanoio GCD of a number

- Every such function must have some terminating criteria- Such functions uses stack to hold the intermediate values

Scope of Variables

- Location of the variable declaration defines its scope- Scope can be of two types

o Local Variableso Global Variables

Declared outside the function Accessible in all functions below the declaration

- Local variables are further two typeso Local to Function – accessible any where in functiono Local to Block – accessible in current block of sub-blocks

- Multiple variables of same name can be created in different scopes- Use scope resolution operator (::) to access the value of global variable

Storage Classes

- Special keyword in C/C++ that defines the location and accessibility of variables- There are four storage classes

o Automatic (auto) – defaulto Static (static)o Register (register)o External (extern)

- Automatic variable get created inside the RAM and created and removed automatically based on their scope

o It is defaulto Use auto keyword

Page 18: my c notes

int n=6; or auto int n=6;

- Register variables are stored inside the CPU registerso Only if register is availableo If register is not available then treated as automatico register keyword is usedo Data upto two bytes can be placed inside the registers

register int n=5;

- Static variable retain their values between different function callso They are initialized only for onceo They are created inside the Heap memoryo They retain their last value until we quit the programo Use static keyword

AssignmentWrite a program to show factorial of a number using recursion of main() and static

02.11.2008

External Storage Class- A method to allow access of global variable across multiple files- Use extern keyword to define the storage class

Passing argument to the functions- When passing arguments to the functions they can be passed as

o Pass by Valueo Pass by Addresso Pass by Reference (only in C++)

Page 19: my c notes

Introduction to Pointers- Special variable that holds address of another variable of its type rather than value- Use indirection operator * to declare and use the pointers

int *p; // p is a pointer to some int type variablechar *c; // c is a pointer to characterdouble *d; // d a pointer to doublevoid *ptr; // ptr is a pointer to anything

Pointers are used for- Indirect Memory Referencing- Dynamic Memory Allocation

Using Indirect Memory Referencing, we can access any memory and update any value indirectly using pointer variables.

int a=5,b=6;int *p;p=&a;*p=79; // value at the address in p (i.e. a) will now be 79

p=&b;*p=35; // value at the address in p (i.e. b) will now be 35

printf(“%d %d”,a,b); //79 35

Dynamic Memory Allocation is used to allocate memory on demand. It can de-allocated when memory is in no more use.

- Use malloc() or calloc() functions to allocate the memory from malloc.h or alloc.h- Use free() to de-allocate the memory

datatype *ptr=malloc(size of one item * number of items)datatype *ptr=calloc(size of one item , number of items)

free(ptr);

Character Pointer and Array

char name[50];name=”Vikas”; // invalid

char *name;name=”Vikas:”; //Valid

Passing Arguments by Value

Page 20: my c notes

- When passing arguments by value, value from actual arguments get copied to formal arguments and new variables get created for formal arguments

o If we make any changes to formal arguments they will not be reflected in actual arguments

o It gives data safety for actual argumentso It is by default

Passing arguments by Address- When passing arguments by address, address of actual argument get copied to

some pointer in formal arguments. If we make any changes using the pointer they will be reflected in actual arguments.

o It is best used when operation need to be done on same location or data be bulky

Passing arguments by Reference (In C++)- When passing argument by reference no pointer variables are used but a reference

or nick name is created for the actual argument- If we make any changes using the pointer they will be reflected in actual

arguments.

05.11.2008

Working with Structures- A user defined data type having dissimilar set of elements- It maintained some data for an entity- Use struct keyword to define the structures

Syntax

struct <structruename>{

//elements;};

Example

Entity library books

struct book{

int bookno;char title[50];char author[50];

};

- Every structure represents a record- Structures do not take any memory until we create the variable of the structure

typeDeclaring variables of structure type

struct <structurename> variable;

Page 21: my c notes

Examplestruct book b1;

- now b1 is a variable of book type having three elements bookno, title and author accessed using a dot operator (.)

b1.bookno=45;

Array of Structures- To hold similar set of multiple records

Using Format Specifiers

%[+-] columnwidth.decimals type

Structure within the structure- A structure can have variable of another structure within it

Another method for Structure Declaration- We can define the structure as pure data type using a keyword typedef- typedef is used to give some name type name for existing types

typedef <oldtype> <newtype>;

typedef unsigned long int uint;

uint x;

typedef struct book books;

books b;

typedef struct{

int d,m,y;} date;

date dob;

Page 22: my c notes

Dynamic Memory Allocation in Structures- Use malloc and get address of the structure

datatype *ptr=malloc(sizeof(structure or variable));

- To access a field using a pointer use(*ptr).fieldname=value;

- Or use arrow operator ->

ptr->fieldname=value;

Assignment

Make a structure for employees with fields empid, name and basic.Input the data and show the report in following format. Calculate the salary as 1.89 times of basic

S.No. Employee Id Name Basic Salary

08.11.2008

File Handling in C

- It is a method to store data permanently on disc- A file on disc is understood and managed by special structure FILE provide

under stdio.h- To work with files on disc we use FILE pointer

Type of Files1. Text Files2. Binary Files

Operations of Files

1. Opening a file2. Reading Contents (Record) from a file3. Add new contents (Record) to the file4. Update Records5. Delete Records6. Search Record7. Close the file

Other Operations1. Deleting a file2. Renaming a file

Function Required for File Handling in Binary Mode

Page 23: my c notes

fopen() function- To open a file

FILE *fp=fopen(“filename”,”purpose and type”);

purpose code can ber readingw writingr+ Read and Write. File Must exist.w+ Write and Read. Create a new file if not found and overwrite the

file if existsType can be

b for Binary Text (Nothing)

Note: If fopen() is unable to open a file then it returns NULL

Example

FILE *fp=fopen(“test.txt”,”rb+”);if(fp==NULL){

fp=fopen(“test.txt”,”wb+”);}

fclose() function- To close the file

void fclose(FILE *fp)

Examplefclose(fp);

fwrite() function- To add a new record into the file or overwrite the current recordSyntax

void fwrite(address of structure variable, size of record, number of records to write, file pointer)

Example

Employee e;fwrite(&e, sizeof(e), 1,fp);

fread() function- To read the records from the file

int fread(address of structure variable, size of record, number of records to read, file pointer)

fseek() function- To set the file pointer inside the file at different locations

Page 24: my c notes

void fseek(file pointer, offset, start point)

Note: The starting point can beStart of the file SEEK_SETEnd of File SEEK_ENDCurrent location in file SEEK_CUR

ExamplesMoving to top of the file to search and show records

fseek(fp, 0, SEEK_SET);Moving to end of the file to add new record

fseek(fp, 0, SEEK_END);Moving to top of the current record to update the record

fseek(fp, -recordsize, SEEK_CUR);

rewind() function- to send the pointer to top of the file

void rewind(file pointer)

Examplerewind(fp);orfseek(fp, 0, SEEK_SET);

remove() function- To delete a file from disc

remove(“filename”);

rename() function- To rename a file from old name to new name

rename(“oldname”,”new name”);

Page 25: my c notes

09.11.2008

Searching the Records- Ask for the record to search- Read all records and compare the key field

Update the Records- Ask for the record to update- Read all records and compare the key field- If found, get new data for that record- Goto top of record- Overwrite the records

Deletion of record- Ask for the record to delete- Read all records and compare the key field- If found,- Open a new file in writing mode- Copy all records to new file except the record to be deleted- Close both the files- Delete the original file- Rename the newly created file into orginal name- Re-open the new file in rb+

Text File OperationsWriting new contentsReading the contents

The contents can be used in three methods1. Character operation2. String operations3. Formatted data operations

fgetc() function- To read a character from given file till EOF reached

char fgetc(filepointer)

fputc() function- to save a character to some file

fputc(char ch, FILE *ptr)

Example

Get a filename from keyboard with path and show its contents

Using Input with Command Line Arguments- When we pass data from command prompt while running a program it goes to main()

function of the program- It is called a command line argument- The main() function will have another syntax

void main(int argc, char *argv[])

Page 26: my c notes

argc count of argumentsargv argument values

- The program we run goes as first argument on index number 0

Note: Whatever we pass with command line is a string. If using any numerical data convert that string into the number using atoi() and atof() functions of math.h

atoi(stringdata) - for string to int conversionatof(stringdata) – for string to float conversion

Example

Get name and age of a person with command line and check for a valid voter

15.11.2008

Pointers for Data Structure Management- Data Structure is collection of related set of data in different formats

o Linear format Linked List Stack Queue

o Non-Linear Graph Tree

Linked List- A linked set of records where we can manage data and address of next record- For such operation we need self referential structures

Types of Linked List1. Single Linked List2. Double Linked List3. Circular Linked List

//single linked liststruct student{

int rollno;char name[30];char course[30];struct student *next;

};//double linked liststruct student{

int rollno;char name[30];char course[30];struct student *prev;struct student *next;

};

Page 27: my c notes

Creating a single linked list- Define a structure with a pointer to hold the address of next records- Use malloc() function to allocate the memory for the records dynamically- When record get deleted use free() to de-allocate the memory to avoid the memory

leakage- Define two global pointers to hold address of first and last records

16.11.2008

Merging Linked List with Files

- Create a global FILE pointer- Open the file before entering in operation loop- Read the records from disc and add them into the linked list- Save the record into the file while adding record into the linked list- Close the file when exit the program

20.11.2008

Working with Queue

- A linear data structure based on FIFO (First-In-First-Out)- Items are added from rear side and deleted from front side

Working with Stacks

- Again a linear data structure base of LIFO (Last-in-first-out)- Items are added and deleted from one end- The item added in the last goes to top- Only one pointer is enough to manage stacks- A stack has three operations

o Push – add new item from topo Pop – read and delete the topmost itemo Peek – only read the topmost item

Difference between typedef and macro definition

- #define is a pre-processor directive whose instructions get replaced before compilationo We can redefine the existing keywords as well

- typedef gives a new name to existing data typeso typedef <old type> <new type>;o

#define char double

printf(“%d”,sizeof(char));

typedef char double; //errortypedef unsigned long int uint; // validuint x;

Page 28: my c notes

Difference between macro and function

#define product(a,b) a*bprintf(“%d”,product(3+4,7+9)); //40 3+4*7+9

#define product(a,b) (a)*(b)printf(“%d”,product(3+4,7+9)); //112 (3+4)*(7+9)

int product(int x, int y){

return x*y;}printf(“%d”,product(3+4,7+9)); //112 7, 16

Multiline Macros- Use line continuation character \ to create multi-line macros

Working with unions

- A data structure very similar to structures- It allocates the memory equivalent biggest element in the union- All elements share the same memory space- It cannot be used for self-referencing and for linked list, stack, queue etc.- It is used for saving the memory space- Use union keyword to declare a union

union test{

//elements};

21.11.2008

Enumerators

- A method to give a name to some value- We can use that name instead of value- Use enum keyword to declare the enumerators- By default numbering starts with 0 and incremented by 1

enum {FALSE, TRUE}; // FALSE 0, TRUE 1

enum {sales=5, marketing, finance, it}; //marketing6 and so on

enum {private=1, public=4, protected=8};

int found=FALSE;ORInt found=0;

- Only int range of values can be used

Page 29: my c notes

Bitfields

- A field used to hold data in bits rather than bytes- Use unsigned data type with such fields along with the bits to be used

Examplestruct employee{

int empid;char name[40];unsigned gender:1; //1 bitunsigned dept:3; //3 bitsunsigned mstatus:1; //1 bitunsigned subject:3; //3 bite

};

Size is now 43 bytes

void pointers

- Special pointers than can hold address of any type- We need to use the cast operator while operating with the void pointer to define the bytes

to be operated

void *ptr;int a=5;double b=5.6;ptr=&a;

*(int *)ptr=45;

ptr=&b;*(double *) ptr=67.99;

Pointer to PointerWhen a pointer variable holds address of another pointer variable, called as pointer to pointer

int a=5;int *ptr=&a;int **ptr1=&ptr;

**ptr1=49;

Getting information about the environmental variables

- Environmental variables are special variables managed by operating system to hold information used by different applications

o PATHo CLASSPATHo PROMPTo TEMP

- To see all such variables use SET command on DOS prompt

Page 30: my c notes

Graphics Programming in C

- A programming in C to write programs in pixel mode rather that text mode- All functions are provided under graphics.h header file- First thing to detect the graphics card inside the machine and initiate the graphics using

its driver file which is stored inside BGI folder of Turbo C- To write a string on the screen use outtextxy() function

o outtextxy(int x, int y, char *str)- To print a formatted output use sprintf() function to print into string then use with

outtextxy()

int x=5, y=10;

char str[100];sprintf(str,”Sum of %d and %d is %d”,x,y,x+y);outtextxy(str);

23.11.2008

Differentiate among break, exit and return?

- break is used to exit from a loop or switch- return statement is used to return the function. A function can have many return

statement but can return only one value.- exit() is used to quit the program. It is provided under process.h header file

o exit(int statuscode)o Returns the status code to the operation systemo Operating system used the status code of previous program when another

executing other dependent program in sequence through a batch fileo Special file get create as .bat to hold the command in sequence