Académique Documents
Professionnel Documents
Culture Documents
2008
Introduction to C
Features of C
TC 3.0
TC 4.5
Borland C++ 5.0
Installing TC 3.0
TURBOC –d c:\
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
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
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
%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];
- 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;
Example
Print the following line
4. Sting literals
a. Enclosed in double quotes
b. Each string is terminated by null character \0
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
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
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
00110
01001
-------
00000
-------
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
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
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
#define n 10
n=11; //Error
OR
const int n=5;
Ternary operator (?:)
- Shortcut to if-else
Example
int g=a>b?a:b;
int g=a>b? (a>c?a:c) : (b>c?b:c);
Switch Statement
switch(variable)
{
case value1: statements; break;
case value2: statements;break;
…
default:statements;
}
Example
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
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)
1
121
12321
121
1
Class assignment
Get two numbers from keyboards and print all prime numbers in range (inclusive)
04.10.2008
Example
int n[5]; //n[0] to n[4]
Array Initialization
- Provide values while creating an array
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
for(i
for(k
{
C[i][k]=0
for(j
C[i][k]+=A[i][j]*B[j][k];
}
String Operations
11.10.2008
Number Sorting
Functions
12.10.2008
Creating User Defined Functions
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()
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];
}
Test Program
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
- 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
Assignment
Write a program to show factorial of a number using recursion of main() and static
02.11.2008
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
free(ptr);
char name[50];
name=”Vikas”; // invalid
char *name;
name=”Vikas:”; //Valid
05.11.2008
Syntax
struct <structruename>
{
//elements;
};
Example
struct book
{
int bookno;
char title[50];
char author[50];
};
- 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
uint x;
books b;
typedef struct
{
int d,m,y;
} date;
date dob;
Dynamic Memory Allocation in Structures
- Use malloc and get address of the structure
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
08.11.2008
File Handling in C
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
Example
FILE *fp=fopen(“test.txt”,”rb+”);
if(fp==NULL)
{
fp=fopen(“test.txt”,”wb+”);
}
fclose() function
- To close the file
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)
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
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
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+
fgetc() function
- To read a character from given file till EOF reached
char fgetc(filepointer)
fputc() function
- to save a character to some file
Example
Get a filename from keyboard with path and show its contents
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
Example
Get name and age of a person with command line and check for a valid voter
15.11.2008
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
16.11.2008
20.11.2008
printf(“%d”,sizeof(char));
Multiline Macros
- Use line continuation character \ to create multi-line macros
union test
{
//elements
};
21.11.2008
Enumerators
int found=FALSE;
OR
Int found=0;
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
};
void pointers
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;
char str[100];
sprintf(str,”Sum of %d and %d is %d”,x,y,x+y);
outtextxy(str);
23.11.2008