Vous êtes sur la page 1sur 30

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
 strlen(), strcpy(), strrev(), strcat(), strcmp() etc.
 To include a header file use any of two methods
o #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
Software Requirements

TC 3.0
TC 4.5
Borland 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 keys


Copy  Ctrl+KC
Move  Ctrl+KV
Delete  Ctrl+KY
De-select  Ctrl+KH
Delete a line -> Ctrl+Y
Undo Alt+Backspace

Basic functions
printf(“message”);  to print on screen in black/white
cprintf(“message”);  to print on screen in defined color
textcolor(colorname);  to define a text color
textbackground(colorname);  to define a text background
gotoxy(column,row);  to send cursor to given position
clrscr();  clear the screen
Compilations options

Alt+F9  Compile
F9  Build
Ctrl+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 byte
o int – 2 or 4 bytes
o float – 4 bytes – 6 dec.places
o double – 8 bytes- 14 dec. places
o void - nothing
 Modified Data Types
o 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 types
o Created using primary and modified types
o Also called as custom types
o Arrays, Pointers, Structures, Unions, Bitfilds etc.

Communicating data with outside world and memory


- 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.
Types of Literals
1. Integral Literals
a. Default is int
b. 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 literals
a. Default is double
b. Use f or F for floats
c. double k=1.1;
d. float p=1.1F;
3. Character Literals
a. Characters are enclosed in single quotes
b. Each character takes one byte
c. Characters and numbers are interchangeable
char ch=’A’;
or
char 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 quotes
iv. \0 – Null Character
v. \t – Horizontal Tab
vi. \n – New Line
vii. \r – Carriage Return
viii. \a or \007 – alert or beep sound

Example
Print the following line

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

4. Sting literals
a. Enclosed in double quotes
b. Each string is terminated by null character \0

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


char 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
Input Methods
scanf()
getch()
getche()
getchar()
gets()

fflush()

Operators
Conditional Statements
Looping 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

Syntax
scanf(“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 Input


getch() – Get a character but don’t echo it. Un-buffered mode
getche() – Get a character and echo it. Un-buffered Mode
getchar() – Get a character. Buffered Mode

For String input


gets(stringvariable) – to get a string including space
Operators

Arithmetic operators
+ - * / %
5/2 2
5.0/2  2.5
5.0/2.0  2.5
5/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.0
float 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 operator
o != Not equals to operator
o >
o >=
o <
o <=
- Returns 1 for true and 0 for false

int n=5>0; //1


int k=5<0; //0

Logical operators
- Combine two conditions or negate the result of a condition
o && Logical And
o || Logical Or
o ! 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

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

Output
Hello1
Problem
int n= 3 || printf(“Hello”);
printf(“%d”,n);

Output
1

Bitwise operators
- The operators that operate on bits are called as bit operators
o & Bitwise And
o | Bitwise Or
o ^ Bitwise XOR
o << Left Shift
o >> Right Shift

int n=6 & 9; //0

00110
01001
-------
00000
-------

int k=67 | 34; //99


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

int k=67 ^ 34; //97

int k=5<<2; //20


64 32 16 8 4 2 1
0 0 0 0 1 0 1
0 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
int n=6;
int k= n++ + 7; //6+7  13

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

Questions
1. 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);

Output
Hello4

64 32 16 8 4 2 1
1 0 0 1 1 1 0
0 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 statement
2. switch statement
3. ternary operator (?:) – having three operands

if statements
- It has multiple syntaxes

[A]
if(condition)
statement;

[B]
if(condition)
{
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;
else
statement;

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

OR
const int n=5;
Ternary operator (?:)
- Shortcut to if-else

Condition ? true part : false part;

Example
int 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 while
o do-while
o for
- while is called as pre-check loop
o 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;

or
for(initialization;condition;updation)
{
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 line
4. Print the whole screen with hearts
5. Print the following for given number of lines
1
22
333
4444

1
12
123
1234

A
BB
CCC
DDDD

A
AB
ABC
ABCD

Explanation
Total lines n
Line 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


*
***
*****

1
121
12321
121
1

Class assignment

Write a program to get a number and print it into words


678  Six Seven Eight
10 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 Array


Syntax
<datatype> <arrayname>[size];

Example
int n[5]; //n[0] to n[4]

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


Double Dimensional Array
- Having rows and columns
o 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 elements


int 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 string


2. Reverse print a string
3. Swapping or interchanging of numbers
a. Method 1
i. Using Third variable
1. int a=5,b=10,temp;
2. temp=a;
3. a=b;
4. b=temp;
b. Method 2
i. Without using third variable
1. int a=5,b=10;
2. a=a+b;
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 line
i. 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 functions
o 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 characters
o 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
• strcmp(s1,s2) To compare two strings
o Returns 0 if s1==s2
o Returns >0 if s1>s2
o Returns <0 if s1<s2
• strcpy(target, source) – To copy string from source to target
• strcat(s1,s2)  To concatenate two strings

12.10.2008
Creating User Defined Functions

- A function has three segments


o Function Declaration
o Function Definition
o 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);


OR
void 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

Get a number and print in Indian Numeral Style

56789  Fifty Six Thousand Seven Hundred Eighty Nine

Next
Recursion
Passing values to the functions
Pointers
Command 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 Numbers
o Pascal Triangle
o Fibonacci Series
o Tower of Hanoi
o 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 Variables
o Global Variables
 Declared outside the function
 Accessible in all functions below the declaration
- Local variables are further two types
o Local to Function – accessible any where in function
o 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) – default
o 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 default
o Use auto keyword

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

- Register variables are stored inside the CPU registers


o Only if register is available
o If register is not available then treated as automatic
o register keyword is used
o Data upto two bytes can be placed inside the registers

register int n=5;

- Static variable retain their values between different function calls


o They are initialized only for once
o They are created inside the Heap memory
o They retain their last value until we quit the program
o Use static keyword

Assignment
Write 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 Value
o Pass by Address
o Pass by Reference (only in C++)
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 variable


char *c; // c is a pointer to character
double *d; // d a pointer to double
void *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


- 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 arguments
o 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
type
Declaring variables of structure type

struct <structurename> variable;


Example
struct 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;
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 Files
1. Text Files
2. Binary Files

Operations of Files

1. Opening a file
2. Reading Contents (Record) from a file
3. Add new contents (Record) to the file
4. Update Records
5. Delete Records
6. Search Record
7. Close the file

Other Operations
1. Deleting a file
2. Renaming a file

Function Required for File Handling in Binary Mode


fopen() function
- To open a file

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

purpose code can be


r  reading
w  writing
r+  Read and Write. File Must exist.
w+  Write and Read. Create a new file if not found and overwrite the
file if exists
Type 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)

Example
fclose(fp);

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

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
void fseek(file pointer, offset, start point)

Note: The starting point can be


Start of the file  SEEK_SET
End of File  SEEK_END
Current location in file  SEEK_CUR

Examples
Moving 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)

Example
rewind(fp);
or
fseek(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”);
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 Operations


Writing new contents
Reading the contents

The contents can be used in three methods


1. Character operation
2. String operations
3. 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[])


argc  count of arguments
argv  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 conversion


atof(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 List


1. Single Linked List
2. Double Linked List
3. Circular Linked List

//single linked list


struct student
{
int rollno;
char name[30];
char course[30];
struct student *next;
};
//double linked list
struct student
{
int rollno;
char name[30];
char course[30];
struct student *prev;
struct student *next;
};
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 top
o Pop – read and delete the topmost item
o Peek – only read the topmost item

Difference between typedef and macro definition

- #define is a pre-processor directive whose instructions get replaced before compilation


o We can redefine the existing keywords as well
- typedef gives a new name to existing data types
o typedef <old type> <new type>;
o
#define char double

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

typedef char double; //error


typedef unsigned long int uint; // valid
uint x;
Difference between macro and function

#define product(a,b) a*b


printf(“%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}; //marketing6 and so on

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

int found=FALSE;
OR
Int found=0;

- Only int range of values can be used


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

Example
struct employee
{
int empid;
char name[40];
unsigned gender:1; //1 bit
unsigned dept:3; //3 bits
unsigned mstatus:1; //1 bit
unsigned 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 Pointer
When 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 PATH
o CLASSPATH
o PROMPT
o TEMP
- To see all such variables use SET command on DOS prompt
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 system
o Operating system used the status code of previous program when another
executing other dependent program in sequence through a batch file
o Special file get create as .bat to hold the command in sequence

Vous aimerez peut-être aussi