Sie sind auf Seite 1von 89

12.08.

2010

Installing Turbo C++ (3.0) – DOS Based – 16 bit software


- Copy Turboc.exe file on C drive or D Drive
- Goto Command Prompt and then D drive (D:)
- Issue the following command on DOS prompt

TURBOC –d

- It creates TC folder with sub folders like BIN, BGI, LIB, INCLUDE etc.
- Start Turbo C++ from TC\BIN\TC.EXE
- Setting the path of directories
o Options  Directories…
o Change the path from C drive to D drive if using the D drive

Types of entry points

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

19.08.2010

Data Types in C

- Special keywords used to define type the type of data and range of data
- Data Types can be of three types
o Primary Data Types
o Modified Data Types
o Derived or User Defined Data Types (UDT)
- C provides five primary types
o char – 1 byte
o int – 2 byte or 4 byte
o float – 4 bytes (6 decimal places)
o double – 8 bytes (14 decimal places)
o void - nothing
- These primary types get modified using special keywords called modifiers
o signed
o unsigned
o short
o long
- Data types modified from primary types using modifiers are called as
modified data types
o char
 signed char or char
 unsigned char
o int
 signed int or int
 unsigned int or unsigned
 short int or short – 2 bytes
 long int or long – 4 bytes
 unsigned short
 unsigned long
o double
 long double – 10 bytes
- Derived data types are user defined data types created as per programmer’s
choice
o Arrays
o Pointers
o Structures
o Unions
o Bitfields
o Enumerators

Creating Variables

- A variable is a name given some memory location to store and retrieve the
data
- Every variable must have some data type associated with it

Example
unsigned rollno;
char gender;
float price;
double weight;
char name[50];
int i,j,k;

Variable Naming Rules


- A variable name can have alphabets (a-z, A-Z), digits (0 to 9) and
underscore only
- Can never start with digit
- Two variables cannot have same name in same scope
- Can be of any length but first 31 characters are significant
Data Input in a Program

C provides various function for data input

1. scanf()
a. To read formatted data of any type
2. gets()
a. To read as string
3. getchar()
a. To get a character in buffered mode
4. getch()
a. To get a character but don’t echo it
b. It uses un-buffered mode
5. getche()
a. To get a character and echo it
b. It uses un-buffered mode

To read formatted data C provides special codes which starts with % called as
format specifiers

%d  decimal number
%o  Octal number
%x or %X  Hexa Decimal Number
%c  Character
%s  String without Space
%[^\n]  Input a string until Enter key is pressed including space
%f  Fixed Float
%e  scientific float
%g  General Float
%lf  double and long double
%ld  Long Integer
%u  Unsigned

Passing data to variables using Literals

- A literal is a value used from our side in any assignment or expression


o int age=56;
o char gender=’M’;
- Literals can be of different types
o Integrals
 Default is int
 Use l or L with long and u or U with unsigned as suffix
• int num=67;
• long p=67L;
• unsigned n=5U;
 If a number starts with 0, treated as octal and if a number
starts with 0x or 0X treated as Hexa Decimal
o Floating Literals
 Default is double
• Use f or F with floats
• double num=6.7;
• float num=6.7f;
o Character Literals
 Enclosed in single quotes
 Characters and numbers are interchangeable
• char ch=’A’;
• char ch=65;
 C provides some special characters called as Escape Sequence
Character s
 Starts with \
• \t Horizontal Tab (8 spaces)
• \n New Line
• \r Carriage Return – Move cursor to start of current
line
• \a or \007 Alert Beap
• \\ print \
• \” print “
• \0 NULL Character
• \b Backspace
o String Literals
 Enclosed in double quotes
 Each string is terminated by NULL character
• char name[]="Amit";

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

21.08.2010

Turbo C Shortcuts (Block Commands)

1. Selection
a. Shift + Arrow keys
2. Copy Text
a. Ctrl+KC
3. Move
a. Ctrl+KV
4. Delete
a. Ctrl+KY
5. De-Select
a. Ctrl+KH
6. Undo
a. Alt+Backspace
7. Delete a line
a. Ctlr+Y
Reading data using scanf() function
- It can any kind of data using format specifier
- Use & (address of operator) to get address of any variable
Test Case
Write a program to input rollno, name and gender of a student

#include<stdio.h>
#include<conio.h>
void main()
{
int rollno;
char gender;
char name[51];
clrscr();
printf("Enter rollno : ");
scanf("%d",&rollno);
printf("Enter Name : ");
fflush(stdin);
scanf("%[^\n]",&name);
printf("Enter Gender [M/F] : ");
fflush(stdin); //clear the keyboard buffer
scanf("%c",&gender);
printf("Roll no is %d, Gender is %c and Name is %s",rollno,gender,name);
}

Note: Use fflush(stdin) function to clear the keyboard buffer if required

Input the characters


- Use any of three function as per needs
o getchar()
o getch()
o getche()

/* Getting a character as input */


void main()
{
char a,b,c;
clrscr();
printf("Enter first character : ");
a=getchar();
printf("\nEnter second character : ");
b=getch();printf("*");
printf("\nEnter third character : ");
c=getche();
printf("\nFirst Character is %c Second is %c and third is %c",a,b,c);
}

Reading Strings

- Use gets() function to read the strings


o gets(variable)
- It takes space as well

How to write a program

Break the program into three components


1. Input
2. Process
3. Output

Input can have one more sub component as variable declaration.

Example
Write a program to input temperate in degree Celsius and convert into
Fahrenheit

Note
C F-32
- = -----
5 9

F=9.0/5 * C + 32

Operators

Arithmetic Operators
+ - * / %

Relational or Comparison operators


== Equals to
!= Not Equals to
> Greater than
>= Greater than or equals to
< Less than
<= Less than or equals to

Note: returns 0 for false and 1 for true

Logical Operators
- Used to combine two conditions or negate result of an expression
o && Logical And
o || Logical Or
o ! Logical Not

Note
1. && returns true if both the conditions are true. If first condition is
false, second condition is not checked.
2. || returns true if any one condition is true. If first condition is true
then, second is not checked
3. Any value other than 0 is treated as true

Example 1
What is the output of following
int num=67 && printf("Hello");
printf("%d",num)

Output
Hello1

Example 2
What is the output of following
int num=67 || printf("Hello");
printf("%d",num)

Output
1

Example 3
What is the output of following
int num=!(67 && printf("Hello"));
printf("%d",num)

Output
Hello0

26.08.2010
Bitwise Operators
- The operators that convert the data into bits and then operate
o & Bitwise And
o | Bitwise Or
o ^ Bitwise XOR
o ~ Bitwise NOT

Truth Tables

&
0 0  0
0 1  0
1 0  0
1 1  1
|
0 0  0
0 1  1
1 0  1
1 1  1
^
0 0  0
0 1  1
1 0  1
1 1  0
~
01
10

Example 1
int num=56 & 34; //32

Example 2
int num = 67 & printf(“Hello”);
printf(“%d”,num);

Note:
|| and | work in different manner. In case of || if the first condition is true
then second one is not checked
Case 1
int x=5 || printf(“Hi”)
printf(“%d”,x);

Output
1

Case 2
int x=5 | printf(“Hi”)
printf(“%d”,x);

Output
Hi7

In of &&, if first condition is false then second one is not checked while in
case & both conditions are always checked.

Assignment Operators
- Used to assign some value to some variable or constant
- A variable can vary or change its value at any moment of time while in
case of constants value once assigned cannot be modified
- Use const keyword to declare a constant
=
+=
-=
*=
/=
&=
|=
^=
++
--

Example
int num=67;
num=num+1; or num+=1 or num++ or ++num;
num=num+6; or num+=6;

const int num=7;


num=8; // compile time error

Post Increment (n++)


- First use the current value then increment it
int num=7;
int x=6 + num++;
printf(“%d %d”,x,num);

Output
13 8

Pre-Increment
- First increment the value then use it

int num=7;
int x=6 + ++num;
printf(“%d %d”,x,num);

Output
14 8

Cast Operator
- To convert one kind of data to another kind of data
- A data type get enclosed in () and used for data conversion is called as
cast operator and process is called as casting
Example
int a=10,b=4;
float x=a/b; //2.0
float y=(float) a/b; //2.5

Full Code
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10,b=4;
float x=a/b;
float y=(float) a/b;
printf("x is %.2f and y is %.2f",x,y);
getch();
}

Output
x is 2.00 and y is 2.50

Conditional Statements
- Some statements used to take decision are called as conditional
statements
- C Provides two statements and one operator for decision making
process
- Statements are
o if statement
o switch statement
- Operator is known as ternary operator and it shortcut of if-else
represented as ?:
o It has three operands

if Statement
- Used to check any kind of condition
Syntaxes

[A] For single statement and single condition


if(condition) statement;
or
if(condition)
statement;
[B]For single condition but multiple statements use a block {}
if(condition)
{
Statements;
}

[C] if-else

if(condition)
statement;
else
statement;

[D] if-else ladder. Executes only one condition


if(condition1)
statement;
else if(condition2)
statement;

[else
statement;]

[E] Nested-if or if within if


When one condition is dependent on other condition, it is called as nested if
if(condition)
{
if(condition)
statement;
}

Example 1
Get a number and check it to be even or odd.

/* Check a number to be even or odd */


#include<stdio.h>
#include<conio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if(num%2==0)
printf("%d is even",num);
else
printf("%d is odd",num);
getch();
}

Case 2
Get a year and check it to be leap year

- A year divisible by 4 but not divisible by 100 or divisible by 400


is called as leap year

/* Check a year to be leap year*/


#include<stdio.h>
#include<conio.h>
int main()
{
int y;
printf("Enter a year : ");
scanf("%d",&y);

if((y%4==0 && y%100!=0) || y%400==0)


printf("%d is a leap year",y);
else
printf("%d is not a leap year",y);

getch();
}

Example 3
Get name and marks of three tests for a students, calculate the average and
print the grade based on following conditions
A+ >=90
A >=70
B+ >=60
B >=50
F for others

#include<stdio.h>
#include<conio.h>
int main()
{
char name[51];
float m1,m2,m3,avg;
printf("Enter your name : ");gets(name);
printf("Enter marks of three subjects : ");
scanf("%f%f%f",&m1,&m2,&m3);
avg=(m1+m2+m3)/3;
if(avg>=90.0f)
printf("Grade is A+");
else if(avg>=70.0f)
printf("Grade is A");
else if(avg>=60.0f)
printf("Grade is B+");
else if(avg>=50.0f)
printf("Grade is B");
else
printf("Grade is F");
getch();
}

Example 4

Get three numbers from keyboard and print the greatest one
Method 1: Nested If

/* Using Nested If */
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,c;
printf("Enter three numbers : ");
scanf("%d%d%d",&a,&b,&c);

if(a>b)
{
if(a>c)
printf("%d is greatest one",a);
else
printf("%d is greatest one",c);
}
else
{
if(b>c)
printf("%d is greatest one",b);
else
printf("%d is greatest one",c);
}
getch();
}

Method 2: If-else ladder


/* Using if-else ladder */
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,c;
printf("Enter three numbers : ");
scanf("%d%d%d",&a,&b,&c);

if(a>b && a>c)


printf("%d is greatest one",a);
else if(b>a && b>c)
printf("%d is greatest one",b);
else
printf("%d is greatest one",c);
getch();
}
29.08.2010

switch statement

- Used to check equality comparisons only

Syntax
switch(variable)
{
case value1: statements; break;
case value2: statements; break;

default: statements;
}

- The variable can be of integral or character type only

Test Example
Write a program to input two numbers and show a menu
1. Add
2. Substract
3. Product
4. Division
5. Remainder

#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,choice;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
printf("\n\n1: Add");
printf("\n2: Substract");
printf("\n3: Product");
printf("\n\nEnter choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Sum is %d",a+b);break;
case 2: printf("Subtraction is %d",a-b);break;
case 3: printf("Product is %d",a*b);break;
default: printf("Invalid choice");
}
getch();
}

Ternary operator

It is shortcut to if-else. It has three operations and called as ternary


operator

Condition? Statement for true : statement for false;

Example 1
Write a program to input two numbers and print greater one.
g=a>b?a:b;

Example 2
Write a program to input three numbers and print greatest one.
g=a>b ? (a>c?a:c) : (b>c?b:c);

Example 3
Write a program to input basic of an employee and print the DA as per rules
basic>=15000 as 85%
basic>=10000 as 70%
basic >=5000 as 50%
else
Nil

Case 1: using if

double da;
if(basic>=15000)
da=basic*0.85;
else if(basic>=10000)
da=basic*0.7;
else if(basic>=5000)
da=basic*.5;
else
da=0;

Case 2: using ternary


da=basic>=15000? basic*.85 : basic>=10000?basic*.7 : basic>=5000?
basic*.5 : 0;
Full Code
/* Input the basic and calculuate DA using ternary operator */
#include<stdio.h>
#include<conio.h>
int main()
{
int basic;
double da;
printf("Enter basic : ");
scanf("%d",&basic);
da=basic>=15000?basic*.85 : basic>=10000?basic*0.7 : basic>=5000?
basic*0.5 : 0;
printf("DA is %lf",da);
getch();
}

Assignment

Write a program to get three numbers, calculate average of that numbers.


Print the grade of the student based on following criteria
90 >= A+
70 >= B+
50> = C+
Else
Fail

Solution
#include<stdio.h>
#include<conio.h>
int main()
{
int x,y,z; float avg;
printf("Enter three numbers : ");
scanf("%d%d%d",&x,&y,&z);
avg=(x+y+z)/3.0;
if(avg>=90)
printf("Grade is A+");
else if(avg>=70)
printf("Grade is B+");
else if(avg>=50)
printf("Grade is C+");
else
printf("Grade is Fail");
getch();
}

Assignment 2

Get a character from keyboard and check it to alphabet, digit or special


character.

Input/Process/Output

Input: Character (char)


char ch;
ch=getchar();
Processing : Condition check  if
if((ch>=’a’ && ch<=’z’) || (ch>=’A’ && ch<’Z’))
printf(“%c is an alphabet”,ch);
else if(ch>=’0’ && ch<=’9’)
printf(“%c is a digit”,ch);
else
printf(“%c is special character”,ch);

Assignment 3
Get an alphabet from keyboard and check it to be vowel or consonant

/* Get a character and check to be alphabet,digit and special character


If a character then check it to be vowel or consonent
*/
#include<stdio.h>
#include<conio.h>
int main()
{
char ch;
printf("Enter a character : ");
ch=getchar();
if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))
{
printf("%c is an alphabet\n",ch);
switch(ch)
{
case 'a' : case 'A' :
case 'e' : case 'E' :
case 'o' : case 'O' :
case 'u' : case 'U' :
case 'i' : case 'I' :
printf("%c is vowel\n",ch);
break;
default:
printf("%c is consonent\n",ch);

}
}
else if(ch>='0' && ch<='9')
printf("%c is a digit",ch);
else
printf("%c is special character",ch);
getch();
}
Assignment 4
Get two numbers from keyboard and interchange (swap) that numbers if
first number is lower than second no. Print both the numbers.

/* Swapping */
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,c;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
if(a<b)
{
c=a;
a=b;
b=c;
}
printf("Numbers are %d and %d",a,b);
getch();
}

Swapping without using third variable


a=a+b;
b=a-b;
a=a-b;

Swapping using bitwise operator XOR

a=a^b;
b=a^b;
a=a^b;

31.08.2010

Looping Statements
- Used to repeat same statement again and again till the condition is
true
- C Provides three looping statements
o while
o for
o do-while

while loop
- To repeat the statement till the condition is true
- It first checked the condition, if condition is true then executes the
statements
- It also called as pre-check loop

Syntax

Initialization;
while(condition)
{
//statements
updation;
}

Example
Write a program to input a number from keyboard print the table of it.
void main()
{
int n,i;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);

i=1;
while(i<=10)
{
printf("%d X %d = %d\n",n,i,n*i);
i++;
}
}
Note: To view the line by execution of a program use F7 and to view values
inside the memory variable use Add Watch (Ctrl+F7)

Example 2
Write a program to input a number and print sum of its digits
void main()
{
int n,d,sum=0;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);

while(n)
{
d=n%10;
sum=sum+d;
n=n/10;
}

printf("sum of digits is %d",sum);

}
Assignment
WAP to input a number and check it to be palindrome.

121  121

for loop

- Another form of while loop


- It is most compact loop
Syntax
for(initialization;condition;updation)
{
statements;
}
- It is mainly used when it is clear how many times a loop will run

Example
Write a program to input a number from keyboard print the table of it.
void main()
{
int n,i;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
for(i=1;i<=10;i++)
printf("%3d X %3d = %4d\n",n,i,n*i);
}

do-while loop

- A loop that always executes at least one irrespective of condition


- It is a post check loop

Syntax

do
{
Statements;
Updation;
}while(condition);

Example
Write a program to print the table of number till the user say Y (Yes) to
create more tables

#include<stdio.h>
void main()
{
int n,i;
char choice;
do
{
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
for(i=1;i<=10;i++)
printf("%3d X %3d = %4d\n",n,i,n*i);

printf("\n\nCreate More Tables [Y/N] ? ");


fflush(stdin);
choice=getchar();
}while(choice=='Y' || choice=='y');

Working with goto statement


- A statement used to jump to any location in the program
- We must have some labeled names to goto certain locations in the
program
- Use : operator define the label names
Sample
top:

if(condition)
goto top;

Example
Use goto statement in place of do-while in last example

/* using goto statement */


#include<stdio.h>
void main()
{
int n,i;
char choice;
top: //label
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
for(i=1;i<=10;i++)
printf("%3d X %3d = %4d\n",n,i,n*i);
printf("\n\nCreate More Tables [Y/N] ? ");
fflush(stdin);
choice=getchar();

if(choice=='Y' || choice=='y')
goto top;

}
02.09.2010

Infinite Loop

- Special loops than can never terminate themselves are called as


infinite loops

while(1)
{
}

for(;;)
{
}

do
{
}while(1);

break statement

- To break a loop or switch statement

Example
Write a program to input a number and show a menu
1. Square
2. Square Root
3. Cube
4. Cube Root
5. Exit

Repeat this menu until 5 is pressed then exit the loop


Solution
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int n,choice;
printf("Enter a number : ");scanf("%d",&n);
for(;;) //infinite loop
{
printf("1 : Square\n");
printf("2 : Square Root\n");
printf("3 : Cube\n");
printf("4 : Cube Root\n");
printf("5 : Exit\n");
printf("\n\nEnter choice : ");scanf("%d",&choice);
if(choice==5) break;
switch(choice)
{
case 1: printf("\nSquare is %d\n",n*n);break;
case 2: printf("\nSquare Root is %f\n",pow(n,1.0/2));break;
case 3: printf("\nCube is %d\n",n*n*n);break;
case 4: printf("\nCube Root is %f\n",pow(n,1.0/3));break;
}
}
}

continue statement

- A statement used to go back to top of the loop by skipping the


commands written below of it

Test Case
- Write a program to print all even numbers between 1 to 100

#include<conio.h>
#include<stdio.h>
int main()
{
int i=1;
while(i++<=100)
{
if(i%2!=0)
continue;
printf("%d\n",i);
}
}
Assignment

Write a program to get a number and check it to be prime number.

Hint: If divide a number from 2 to n-1 and remainder is 0 then not a


prime number else a prime number.

void main()
{
int n,d,status=0;
printf(“Enter a number : “);scanf(“%d”,&n);

for(d=2;d<n;d++)
{
if(n%2==0)
{
status=1;
break;
}
}
if(status==0)
printf("%d is a prime number",n);
else
printf(“%d is not a prime no”,n);

Assignment 2
Write a program to print all prime numbers from 1 to 100

Assignment 3
Write a program to print tables 3 to 10

Assignment 4
Write the program to print all ASCII characters from 1 to 255

Assignment 5
Write a program to get a number and fill the full screen with the ASCII
character corresponding to that number.
Homes Assigments
[A]
A
BB
CCC
DDD
EEEEE

[B]
A
AB
ABC
ABCD
ABCDE

[C]
1
12
123
1234

[D]
1
22
333
4444
55555

[E]
*
***
*****
[F]
1
121
12321
07.09.2010
Working with Strings
- A string is made of characters
- Every string is terminated by NULL character \0
- Different cases
o Get a string and print length of the string
o Get a string and reverse print it
o Get a string and check it to be palindrome
o Write a program to get login and password and just show them

Assignment
1. Write a program to get a string and a character. Show the positions
where that character is found in the string and total number of
occurrences of the character in the string.
2. Get a string and print the following from that string
a. Characters :
b. Digits
c. Special Character :
d. Spaces:

Arrays

- A variable that can hold multiple values of similar data type in


continuous locations
- To declare an array use square brackets [] with size of array and type
of array

int num[10]; // num can contain 10 int type values

- Each element of an array can be differentiated by a number called as


index number or subscript number. It always starts with 0

Arrays can be of three types


1. Single Dimensional Array
2. Two Dimensional Array
3. Multi Dimensional Array

Single Dimensional Array can have only one row.


int num[3];
char name[51];
double salary[10];
Two Dimensional array can have rows and columns.
int num[3][4]; // 3 rows and 4 columns
char names[10][51];

Multi Dimensional array can have more than 2 dimensions


int num[2][3][4];

Example 1
Write a program to input 10 numbers and print their sum and average.
void main()
{
int num[10],i,sum=0;
float avg;
clrscr();
for(i=0;i<10;i++)
{
printf("Enter number %d : ",i+1);
scanf("%d",&num[i]);
}
for(i=0;i<10;i++)
sum=sum+num[i];
avg=sum/10.0;
printf("Sum is %d and Average is %.2f",sum,avg);
}

Using Macros
- A system to define the constants and shortcuts for various commands
and functions
- Use #define pre-processor directive

#define SIZE 5
#define P printf
#define S scanf
#define go(r,c) gotoxy(c,r)
#define CLS clrscr()

Different between #include <> and #include “ ”

- Use <> we can include only standard head files while using “ ” we can
include standard as well as user defined header files
Example 2
Write a program to input 10 numbers and print the biggest one and smallest
one

Assignment
Write a program to input some numbers and print the smallest and biggest
out of all those number.

14.09.2010

Two Dimensional Array

- An array that can have rows and columns

int num[4][5]; // 4 rows and 5 columns

Example 1
Write a program to input data in 3x4 matrix and display the values in matrix
format

#include<stdio.h>
#include<conio.h>
#define ROWS 3
#define COLS 4
int main()
{
int num[ROWS][COLS],r,c;
for(r=0;r<ROWS;r++)
{
for(c=0;c<COLS;c++)
{
printf("Enter data in [%d][%d] : ",r,c);
scanf("%d",&num[r][c]);
}
}
printf("\n\nData in Matrix form is \n");
for(r=0;r<ROWS;r++)
{
for(c=0;c<COLS;c++)
printf("%4d",num[r][c]);
printf("\n");
}
getch();
}
Example 2
Write a program to input an array of 3x4 and print transpose of it.
#include<stdio.h>
#include<conio.h>
#define ROWS 3
#define COLS 4
int main()
{
int num[ROWS][COLS],r,c;
for(r=0;r<ROWS;r++)
{
for(c=0;c<COLS;c++)
{
printf("Enter data in [%d][%d] : ",r,c);
scanf("%d",&num[r][c]);
}
}
printf("\n\nData in Matrix form is \n");
for(r=0;r<ROWS;r++)
{
for(c=0;c<COLS;c++)
printf("%4d",num[r][c]);
printf("\n");
}

printf("\nTraspose is\n");
for(r=0;r<COLS;r++)
{
for(c=0;c<ROWS;c++)
printf("%4d",num[c][r]);
printf("\n");
}
getch();
}
Example 3
Write a program to input two arrays of 3x4 and 4x5 and produce the product
of those arrays
 Output array will be 3x5

[A]ixj X [B]jxk  [C] ixk

C[i][k]=C[i][k]+A[i][j]xB[j][k];

#include<stdio.h>
#include<conio.h>
int main()
{
int a[3][4],b[4][5],c[3][5];
int i,j,k;
printf("Enter data in First Array\n");
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
printf("Enter data in a[%d][%d] : ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\nEnter data in second array\n");
for(j=0;j<4;j++)
{
for(k=0;k<5;k++)
{
printf("Enter data in b[%d][%d] : ",j,k);
scanf("%d",&b[j][k]);
}
}

for(i=0;i<3;i++)
for(k=0;k<5;k++)
{
c[i][k]=0;
for(j=0;j<4;j++)
c[i][k]=c[i][k]+a[i][j]*b[j][k];
}

printf("\nFirst Matrix is \n");


for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
printf("%4d",a[i][j]);
printf("\n");
}
printf("\nSecond Matrix is \n");
for(j=0;j<4;j++)
{
for(k=0;k<5;k++)
printf("%4d",b[j][k]);
printf("\n");
}
printf("\nProduct of Matrices is \n");
for(i=0;i<3;i++)
{
for(k=0;k<5;k++)
printf("%4d",c[i][k]);
printf("\n");
}

getch();

}
Functions
- A function is a set of statements given some name to avoid repetition of
same statements again and again
- Functions can of two types
o Library Functions
o User Defined Functions (UDF)
- Library functions are provided with the compiler in special files called as
header files (.h)
- User Defined Functions are created by programmers as per choice

ctype.h Header file

- Provides various functions for characters


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

Example
Write a program to input a character and check it to be alphabet, digit or special
character. Check whether the character is in upper or lower case.

#include<ctype.h>
#include<conio.h>
#include<stdio.h>
int main()
{
char ch;
printf("Enter a character : ");
ch=getchar();
if(isalpha(ch))
{
if(isupper(ch))
printf("%c is upper alphabet",ch);
else
printf("%c is lower alphabet",ch);
}
else if(isdigit(ch))
printf("%c is a digit",ch);
else
printf("%c is a special character",ch);

getch();
}

Example 2
Write a program to input a string and convert into upper case.

/* Get a string and convert into upper case */


#include<conio.h>
#include<ctype.h>
#include<stdio.h>
int main()
{
char str[100]; int i=0;
printf("Enter a string : ");
gets(str);
while(str[i]!='\0')
{
if(islower(str[i]))
putchar(toupper(str[i]));
else
putchar(str[i]);

i++;
}
getch();

Assignment
WAP to get a string and operate according to an option in menu
1. Upper Case
2. Lower Case
3. Title Case
4. Toggle Case
5. Sentence Case
6. Reverse
7. Exit

Using putchar() function

- To output a character
o putchar(ch)

Functions of string.h Header file

1. strlen(str)
a. returns length of string
2. strupr(str)
a. To convert a string into upper case
3. strlwr(str)
a. To convert a string into lower case
4. strrev(str)
a. To reverse a string
5. strcpy(target, source)
a. To copy one string into other string
6. strcmp(s1,s2)
a. To compare two strings
b. Compare as case sensitive
i. s1==s2 returns 0
ii. s1>s2 returns >0
iii. s1<s2 returns <0
7. strcmpi(s1,s2)
a. Compare two string as case in-sensitive
8. strcat(s1,s2)
a. Concatenate two strings

Example
Write a program to input a string and convert into upper case, lower case, reverse
of it and length of it

#include<string.h>
#include<conio.h>
#include<stdio.h>
int main()
{
char str[100],temp[100];
printf("Enter a string : ");
gets(str);
strcpy(temp,str);
printf("Length is : %d\n",strlen(temp));
printf("Upper is : %s\n",strupr(temp));
printf("Lower is : %s\n",strlwr(temp));
printf("Reverse is : %s\n",strrev(str));
getch();
}
16.09.2010
Sorting of Numbers/Strings

- First get a array


- Take numbers one by one, compare all numbers below of it and
replace the lower numbers by bigger numbers (using swapping)

Example 1
#include<stdio.h>
#include<conio.h>
#define SIZE 10
int main()
{
int ar[SIZE], i,j,temp;
printf("Enter %d numbers : ",SIZE);
for(i=0;i<SIZE;i++)
scanf("%d",&ar[i]);
for(i=0;i<SIZE;i++)
{
for(j=i+1;j<SIZE;j++)
{
if(ar[j]<ar[i])
{
temp=ar[i];
ar[i]=ar[j];
ar[j]=temp;
}
}
}

printf("\nSorted Numbers are \n");


for(i=0;i<SIZE;i++)
printf("%d\n",ar[i]);

getch();
}
Example 2
/* Using strcat() */
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char fname[]="Rakesh",lname[]="Kumar";
char fullname[100]="";
strcat(fullname,fname);
strcat(fullname," ");
strcat(fullname,lname);
printf("Full Name is : %s",fullname);
getch();
}

Creating User Defined Functions (UDF)

- When we want to create our own functions they are called as User
Defined Functions
- A function has three segments
o Function Declaration
o Function Definition
o Function Call

Function Declaration
- Used to define the name of function, number of arguments, type of
arguments and return type
- Based of return type, functions can be divided in two types
o void functions
o non-void functions
- void functions do not return any value
- non-void functions must return some value using return statement
- Default return type is int

Example 1
Write a function that takes a number as argument and prints cube of it

void cube(int num); or void cube(int);


Example
Write a function that takes a number and returns factorial of it.
long factorial(int n); or long factorial(int);
Function Definition

When providing working to a function, it is called as function definition. The


arguments used while create a function are called as formal arguments.

void cube(int n)
{
printf(“Cube of %d is %d”,n, n*n*n);
}

long factorial(int num)


{
long f=1; int i;
for(i=1;i<=num;i++)
f=f*i;
return f;
}

Function Call
- When we use a function it is call as function call
- The argument passed while calling a function is called as actual
argument

Full Program Code


#include<stdio.h>
#include<conio.h>
void cube(int num); //function declaration
long factorial(int n);
int main()
{
int n; long fact;
printf("Enter a number : ");
scanf("%d",&n);
cube(n); //function call
fact=factorial(n);
printf("\nFactorial of %d is %ld",n,fact);
getch();
}

void cube(int n) //function definition


{
printf("Cube of %d is %d",n,n*n*n);
}
long factorial(int num)
{
long f=1; int i;
for(i=1;i<=num;i++)
f=f*i;
return f;
}

Note:
If function definition is provide before main() then function declaration is no
more required

Example
#include<stdio.h>
#include<conio.h>

void cube(int n) //function definition


{
printf("Cube of %d is %d",n,n*n*n);
}
long factorial(int num)
{
long f=1; int i;
for(i=1;i<=num;i++)
f=f*i;
return f;
}
int main()
{
int n; long fact;
printf("Enter a number : ");
scanf("%d",&n);
cube(n); //function call
fact=factorial(n);
printf("\nFactorial of %d is %ld",n,fact);
getch();
}

Note
A function can have many return statements but can return only one value

Recursion
- A process where a function calls itself
- When a function calls itself within it, it is called as recursive function
and the process is called as recursion
- Each of such function must have some terminated criteria
- Such functions use the stack to hold intermediate values

Using Stack
void main()
{
int a=5,b=6,c=7;
printf("%d %d %d");
}

Output
765

21.09.2010

Pascal Triangle
- A triangle that contains first column as 1 and last column as 1 and all
other as sum of two elements in upper row

Assignment
Write a program to print the Pascal Triangle for given number of rows.

- Calculate GCD (Greatest Common Divisor) of a number


o Deduct the number from bigger to lower till both are same

Scope of variables

- Variables can be of two types


o Global Variables
o Local Variables
- When a variable get declared outside a function, it is called as global
variable. It can be used in all the functions below declaration
- Local variables can again be of two types
o Local to function
o Local to Block (Block variables)

int a=5; //global variable


void square();
void main()
{
int b=6; //local to function
if(b>=6)
{
int c=7; //local to block
printf(“%d”,b*c);
}
square();
}
void square()
{
printf(“Square of %d is %d”,a,a*a);
}

- Two variable with same name cannot be created in same scope but
can be created in different scopes

int a=5; //global variable


void square();
void main()
{
int a=6; //local to function
clrscr();
if(a>=6)
{
int a=7; //block variable
printf("Product of %d and %d is %d",a,a,a*a);
}
square();
}
void square()
{
printf("\nSquare of %d is %d",a,a*a);
}
To access a global variable with same name as local variable use Scope
Resolution Operator (::)

int a=5; //global variable


void square();
void main()
{
int a=6; //local to function
clrscr();
if(a>=6)
{
int a=7; //block variable
printf("Product of %d and %d is %d",a,::a,a*::a);
}
square();
}
void square()
{
printf("\nSquare of %d is %d",a,a*a);
}

Storage Classes

- Special keywords used to define the storage location and life of a


variable
- C Provides four storage class
o Automatic (auto) – Default
o Static (static)
o Register (register)
o External (extern)

Automatic Storage Class


- All variable get created in RAM and destroyed automatically when goes
out of scope

int num; or auto int num;

Static Storage Class


- To retain the variable in memory until will quit the program
- They initialize only for once
- Use static keyword with such variables
Register Storage Class

- It is used to make a request to place some variable into CPU register


- If register is available in CPU then created inside CPU else treated as
local variable.
- Use register keyword
- The variables that can be placed inside a register can only be int type
or char type

void counter()
{
static int i=1;
printf("%d\n",i);
i++;
}
void main()
{
register int n;
clrscr();
for(n=1;n<=10;n++)
counter();
}

External Storage Class


- A storage class that allows to access a global variable in one file of a
project to other file of project
- Use extern keyword to define a variable as external

Passing Arguments to the functions

- Argument can be passed using three types


o Pass by value or call by value
 C and C++ both
o Pass by Address or call by Address
 C and ++ both
o Pass by Reference or Call by Reference
 Only C++
Introduction to Pointers

A variable that is used for


- Dynamic Memory Allocation
- Indirect Memory Referencing

A pointer variable can hold address of another variable.

Declaring a pointer
- Use indirection operator (*)
o int *p; //p is a pointer to some int type variable
- Such variable can hold address of its type and never a value
o char *ch;
o double *k;
o void *ptr;
- Size of pointer variable can be 2 bytes or 4 bytes depending on
operating system

Indirect Memory Referencing

- Modifying or accessing data in some memory using indirect means is


called as indirect memory referencing

Example
int a=5,b=6;
int *p; // p is a pointer that hold address of some int type variable
p=&a;
*p=20; // value at the address in p is now 20
p=&b;
*p=40;

Dynamic Memory Allocation

- Pointers allow to allocate the memory dynamically at run time


- C provides some function to work with memory memanagement
o malloc()
o calloc()
o free()
o realloc()
- malloc() is used allocate any amount of memory using chained links
- calloc() allocates data in continuous locations and upto 64KB only
- calloc() initialize is created memories with 0 while malloc() to not
initialize its memory

Syntax
datatype *variable=(datatype *) malloc(n*sizeof(datatype));
datatype *variable=(datatype *) calloc(n,sizeof(datatype));

Example
Write a program to ask the user to create the memories and show data in
that memory

#include<alloc.h>
void main()
{
int n,*p,*q;
int i;
clrscr();
printf("Number to allocate : ");
scanf("%d",&n);
p=(int *)malloc(n*sizeof(int));
q=(int *)calloc(n,sizeof(int));
for(i=0;i<n;i++)
printf("%d\n",*(p+i)); // value at the address
for(i=0;i<n;i++)
printf("%d\n",*(q+i)); // value at the address
}

Example 2
WAP to ask the user the number of item. Input data for that numbers and
print the sum of all those numbers.

#include<alloc.h>
void main()
{
int n,*p,i,sum=0;
clrscr();
printf("Enter number of items : ");
scanf("%d",&n);
p=(int *) malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
printf("Enter number %d : ",i+1);
scanf("%d",p+i);
}
printf("\nNumbers are \n");
for(i=0;i<n;i++)
{
printf("%d\n",*(p+i));
sum=sum+*(p+i);
}
printf("Sum is : %d",sum);
free(p); //deallocate the memory
}

Relationship between array and pointer

Address
p+i  &p[i]
i+p  &i[p]

Value
*(p+i)  *(i+p) 
p[i]  i[p]

Passing arguments to the functions

- Argument can be passed using three types


o Pass by value or call by value
o Pass by address or call by address
o Pass by reference or call by reference

In case of pass by value, the values get passed from actual arguments to
formal arguments, new variables get created as formal arguments. If we
make any changes to formal arguments they will not be reflected in actual
arguments. It gives data safety to our variables.

/* passing argument by value */


void change(int n)
{
n=n+10;
}
void main()
{
int n=6;
change(n);
clrscr();
printf("%d",n);
}

In case of pass by address, the address of a actual argument get passed to


formal arguments. If we any change to that address they will be reflected in
actual argument.

/* passing argument by address */


void change(int *n)
{
*n=*n+10;
}
void main()
{
int n=6;
change(&n);
clrscr();
printf("%d",n);
}

In case of pass by reference, reference of actual argument get passed to


formal argument. Both share the same memory location. If we make any
changes to formal arguments, they will be reflected in actual arguments. No
pointer are required. Allowed only in C++

#include<stdio.h>
#include<conio.h>
/* passing argument by reference */
void change(int &n)
{
n=n+10;
}
void main()
{
int n=6;
change(n);
clrscr();
printf("%d",n);
}

28.09.2010

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

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

name[0]=’V’;//correct
name[1]=’i';

strcpy(name,”Vikas”);

char *str;
str=”Vikas”;//correct

Array of Pointers

- If we want to multiple addresses of similar type of data we can define


array of pointers

int *n[3];

n is an array of three int type pointers

int x=5,y=6,z=7;
n[0]=&x;
n[1]=&y;
n[2]=&z;

*n[0]=66;
Printf(“%d”,n); //66
Using command line arguments

- When running a program from command prompt, we can pass some


data to the program directly in front of the command
- The data get entered into the program using main()
- Such input is called as non-interactive input or command line
arguments
- New type of entry point is required

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

- Here argc provides count of arguments and argv provides arguments


values

Test Program
WAP to input some names into the program and show the total number of
arguments and their locations

Note: Whatever we pass to main() it is string type data. If getting input a


numeric data, first convert the data into number using built-in functions of
stdlib.h header file
atoi()  string to int convertion
atof()  string to float conversion

Example1
Write a program to input two numbers from command line and show product
of those numbers.

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


{
if(argc<3)
{
printf("Syntax is : Product <num1> <num2>");
return;
}
else
{
int a,b;
a=atoi(argv[1]);
b=atoi(argv[2]);
printf("Product of %d and %d is %d",a,b,a*b);
}
}

Assignment

WAP to input name and age of a person from command line and check it to
be valid voter.

Interview Question
Differentiate among break, return and exit()

break is used to break the switch or loop


return is used to quit a function
exit() is used quit the application

Structures

- A user defined data type to manage dissimilar kind of data under a


name
- Use struct keyword to define the structures
- Data get collected about an entity or tagname
- Every structure denotes a record

Declaring a structure

struct <structname or tagname>


{
//elements
};

Example
struct employee
{
int empid;
char gender;
char name[51];
double salary;
};
struct book
{
int bookno;
char title[51];
int price;
};

Creating variables of structure type


struct book b;

Accessing members of a structure


- Use dot (.) operator

b.bookno=67;
gets(b.title);

Array of Structures

- Used to multiple records of similar type

struct book b[5];

Example
WAP to create a structure to hold of 5 books and show them in formatted
columns

S.No. Book No Title Price

Assignment

Create a structure for an employee to manage empid, name and basic.


Show the following report

Emp Id Name Basic DA HRA PF Net Salary

DA is 80% of basic
HRA is 35% of basic
PF is 12% of basic
Net => basic+da+hra-pf

30.09.2010

Using typedef keyword

- Used to redefine an existing type to new type

typedef <current type> <new type name>;

Example
typedef unsigned long int uint;

uint x;

typdef struct book books;

books b;

Another way of creation of structures

typedef struct
{
int empid;
char name[30];
int basic;
} Employee;

Employee e;

Example

#include <stdio.h>
#include<conio.h>
#define COUNT 5
typedef struct
{
int empid;
char name[30];
int basic;
} employee;
int main()
{
employee e[COUNT]; int i;
double da,hra,pf,net;
printf("Enter data for %d employees : \n",COUNT);
for(i=0;i<COUNT;i++)
{
printf("Employee Id : ");scanf("%d",&e[i].empid);
printf("Name : ");fflush(stdin);gets(e[i].name);
printf("Basic : ");scanf("%d",&e[i].basic);
}
printf("\n%8s %-25s %8s %8s %8s %8s
%9s","EmpId","Name","Basic","DA","HRA","PF","Net");
for(i=0;i<COUNT;i++)
{
da=0.8*e[i].basic;
hra=0.35*e[i].basic;
pf=0.12*e[i].basic;
net=e[i].basic+da+hra-pf;
printf("\n%8d %-25s %8d %8.2lf %8.2lf %8.2lf
%9.2lf",e[i].empid,e[i].name,e[i].basic,da,hra,pf,net);
}
printf("\n\nPress any key to continue...");
getch();
}

Pointer to Structure

- We can define a pointer to some structure an can access that structure


variables using dot (.) or using special operator called as arrow
operator (->)

employee *p=(employee *) malloc(sizeof(employee));

- To access members of such structure pointer use following methods


o (*p).empid=500;
- Replace the *, (, ) and . with another operator ->
o P->empid=500;
Note: For general structures use dot (.) operator and for pointer to structure
use arrow (->) operator
Test Example
Create a structure for a student and allocate the memory at runtime. Use
the allocated memory to get some record and just show it.

#include <stdio.h>
#include<conio.h>
#include<malloc.h>
typedef struct
{
int rollno;
char name[30];
char course[30];
} student;
int main()
{
student *s;
s=(student *) malloc(sizeof(student));
printf("Enter Roll No : ");
scanf("%d",&s->rollno);
printf("Name : ");
fflush(stdin);
gets(s->name);
printf("Course : ");
fflush(stdin);
gets(s->course);
printf("\n\nData is \n");
printf("Name is %s, Roll No is %d and Course is %s",s->name,s->rollno,s->course);
getch();
}

Memory Allocation Types

Memory can be allocated using two methods


1. Early Binding
2. Late Binding or Dynamic Binding

In case of early binding, the compiler has pre-knowledge about the memory
requirements while in case of late binding, memory is allocated at runtime
and compiler has no idea about the memory allocation.

In case of late binding speed of operation is slower than early binding.

student s; // early binding


student *s;//late binding

File Handling in C

- A method to save data to a file so that we can access it later on


- To work with files C provides a built structure called FILE under
stdio.h header file
- File can be of two types
o Text Files
o Binary Files
- To work with file we need to open it for some purpose and defined
mode
o r  open file for read only in text mode
o w  open file for write only in text mode
o r+  open file for read and write in text mode
 Open the file if exists else return NULL
o w+  open file for write and read in text mode
 Creates a new file if not found and overwrites the contents
if exists
o rb  open file for read only in binary mode
o wb  open file for write only in binary mode
o rb+  open file for read and write in binary mode
 Open the file if exists else return NULL
o wb+  open file for write and read in binary mode
 Creates a new file if not found and overwrites the contents
if exists

Functions for text mode


fopen()
fclose()
fgetc()
fputc()
fgets()
fputs()
fprintf()
fscanf()
Opening a file for reading purpose only

FILE *fp=fopen(“test.txt”,”r”);
if(fp==NULL)
{
printf(“unable to open file”);
return;
}

NULL is a pre-define value in stdio.h to indicate no address

Character operations

Use function fgetc() and fputc()

char fgetc(FILE *fp)

If no more character found return the EOF or -1

Closing a file

Use fclose() function with file pointer

fclose(fp);

Test Case
WAP to read contents of a file and show them on screen

#include<stdio.h>
#include<conio.h>
int main()
{
char fname[100];
char ch;
FILE *fp;
printf("Enter the file name : ");
gets(fname);
fp=fopen(fname,"r");
if(fp==NULL)
{
printf("Unable to open file");
getch();
return;
}
printf("Contents are\n");
for(;;)
{
ch=fgetc(fp);
if(ch==EOF)
break;
else
putchar(ch);

}
fclose(fp);
getch();
}

WAP to read contents of a contents of a file, convert them into caps and
write into a new file. Use command line to read the filename.

Note: Open two files, first for reading and a new file for writing. Read
character by character and write by converting into caps. Use toupper()
function of ctype.h to convert a character into caps.

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
int main(int argc, char *argv[])
{
FILE *source,*target;
char ch;
if(argc<3)
{
printf("Syntax is : MyCopy <sourcefile> <targetfile>");
return;
}
source=fopen(argv[1],"r");
target=fopen(argv[2],"w");

while((ch=fgetc(source))!=EOF)
{
fputc(toupper(ch),target);
}
fclose(source);
fclose(target);
}

Working with records

- First create a structure and its variable


- Input the data into structure variable
- Use special method for records based operation in binary mode
o fwrite()
o fread()
o fseek()
o rewind()
- Some additional functions are also used
o remove(filename)
 To remove a file from disc
o rename(sourcename, targetfilename)
 To rename a file
fwrite() function
- To write a record into a file
o void fwrite(address of record,size of record, number of records, file
pointer)

fread function
- to read records from file
o int fread(address of record,size of record, number of records, file
pointer)

fseek() function
- Use to set the file pointer in the file
- fseek(file pointer, offset, start point)
- start points can be
o SEEK_SET
 Beginning of file
o SEEK_END
 End of file
o SEEK_CUR
 Current position in file

Example
fseek(fp,0,SEEK_SET);
Set pointer to beginning of file
fseek(fp,0,SEEK_END);
Set pointer to end of file
fseek(fp,-rsize,SEEK_CUR);
Set pointer to beginning of current record

rewind()
To set file pointer to beginning of file
rewind(file pointer)

Example
WAP to manage records for an employee with following details
1. empid
2. name
3. basic

Steps for different options in file handling

1. Add new records


a. Read contents of record
b. First goto bottom file
c. Write the record
2. Reading all the records
a. Goto start of file
b. Read the records till end of file reached
3. Search a record
a. Goto top of the file
b. Read the record
c. Compare the record with search value
4. Update a record
a. Search the record
b. Get new data
c. Overwrite the record
5. Delete a record
a. Search the record to delete
b. Open a new file in writing mode
c. Write all records into new file except the record to be deleted
d. Close both the files
e. Remove the original file
f. Rename new file name with original name
g. Reopen the file in read/write mode

#include<stdio.h>
#include<conio.h>
typedef struct
{
int rollno;
char name[31];
char course[15];
}student;

student s;
int size;
FILE *fp;
void add()
{
printf("\nEnter Roll No : ");scanf("%d",&s.rollno);
printf("Name : ");fflush(stdin);gets(s.name);
printf("Course : ");fflush(stdin);gets(s.course);
fseek(fp,0,SEEK_END); //bottom of file
fwrite(&s,size,1,fp);
printf("\n\nRecord Added....");
getch();

}
void show()
{
rewind(fp);
while(fread(&s,size,1,fp))
{
printf("\n%d %s %s\n",s.rollno,s.name,s.course);
}
printf("\n\nPress any key to continue...");
getch();
}
void search()
{
int r,found=0;
printf("Enter rollno to search : ");
scanf("%d",&r);

rewind(fp);
while(fread(&s,size,1,fp))
{
if(s.rollno==r)
{
found=1;
break;
}
}
if(found)
printf("Record found");
else
printf("Record Not found");
printf("\n\nPress any key to continue...");
getch();
}
void update()
{
int r,found=0;
printf("Enter rollno to update : ");
scanf("%d",&r);

rewind(fp);
while(fread(&s,size,1,fp))
{
if(s.rollno==r)
{
found=1;
break;
}
}
if(found)
{
printf("Old name : %s New Name ? ",s.name);
fflush(stdin);gets(s.name);
printf("Old Course : %s New Course ? ",s.course);
fflush(stdin);
gets(s.course);
fseek(fp,-size,SEEK_CUR);
fwrite(&s,size,1,fp);
printf("\nRecord Updated....");
getch();
}
else
printf("Record Not found");
printf("\n\nPress any key to continue...");
getch();
}
void del()
{
int r,found=0;
printf("Enter rollno to delete : ");
scanf("%d",&r);

rewind(fp);
while(fread(&s,size,1,fp))
{
if(s.rollno==r)
{
found=1;
break;
}
}
if(found)
{
FILE *temp=fopen("temp.dat","wb");
rewind(fp);
while(fread(&s,size,1,fp))
{
if(s.rollno!=r)
fwrite(&s,size,1,temp);
}
fclose(fp);
fclose(temp);
remove("student.dat");
rename("temp.dat","student.dat");
fp=fopen("student.dat","rb+");
printf("\nRecord deleted....");
}
else
printf("Record Not found");
printf("\n\nPress any key to continue...");
getch();
}

int main()
{
int choice;
size=sizeof(student);
fp=fopen("student.dat","rb+");
if(fp==NULL)
{
fp=fopen("student.dat","wb+");
}

for(;;)
{
printf("1 : Add Student\n");
printf("2 : Show Students\n");
printf("3 : Search Student\n");
printf("4 : Update Student\n");
printf("5 : Delete Student\n");
printf("6 : Exit\n");
printf("\n\nEnter choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1: add();break;
case 2: show();break;
case 3: search();break;
case 4: update();break;
case 5: del();break;
case 6:fclose(fp); exit(0);
}
}

}
Data Structures
Special types used to manage data in memory
Can be of two types
1. Linear Data Structures
2. Non-Linear Data Structures

Linear Data Structures can be


1. Linked List
2. Stack
3. Queue

Non-Linear Data Structures can be


1. Tree
2. Graph

Linked List

- A linear data structure to manage linked set of dynamic records


- Can be of three types
o Single Linked List
o Double Linked List
o Circular Linked List
- Every record must have two things
o Data
o Address of next record
- Every structure used to manage the record must be self referential
structure

Self Referential Structure

- A structure that contains the data elements and a pointer that can hold
address of another record of same structure type

struct student
{
int rollno;
char name[31],course[15];
struct student *next;
};
Creating Single Linked List

- Create a structure having data and one pointer for next record
- Manage two global pointer for first and last records
- While adding the records used malloc() function to allocate the
memory on demand
- Link the last record with new records

#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[31];
char course[15];
struct student *next;
};

struct student *first,*last;

void add()
{
struct student *temp=(struct student *)malloc(sizeof(struct student));
printf("Roll No : ");scanf("%d",&temp->rollno);
printf("Name : ");fflush(stdin);gets(temp->name);
printf("Course : ");fflush(stdin);gets(temp->course);
temp->next=NULL;
if(first==NULL)
first=last=temp;
else
{
last->next=temp;
last=temp;
}
printf("\nRecord Added...");
getch();
}
void show()
{
struct student *ptr;
for(ptr=first;ptr!=NULL;ptr=ptr->next)
{
printf("\n%d %s %s",ptr->rollno,ptr->name,ptr->course);
}
printf("\nPress any key to continue...");
getch();
}
int main()
{
int choice;
first=last=NULL;
for(;;)
{
printf("\n1: Add Record\n");
printf("\n2: Show Records\n");
printf("\n3: Exit\n");
printf("\n\nEnter choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1: add();break;
case 2: show();break;
case 3: exit(0);
}
}

Operations in Single Linked List

1. Add Element
2. Traverse
3. Search
4. Update
5. Delete

#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[31];
char course[15];
struct student *next;
};

struct student *first,*last;

void add()
{
struct student *temp=(struct student *)malloc(sizeof(struct student));
printf("Roll No : ");scanf("%d",&temp->rollno);
printf("Name : ");fflush(stdin);gets(temp->name);
printf("Course : ");fflush(stdin);gets(temp->course);
temp->next=NULL;
if(first==NULL)
first=last=temp;
else
{
last->next=temp;
last=temp;
}
printf("\nRecord Added...");
getch();
}
void show()
{
struct student *ptr;
for(ptr=first;ptr!=NULL;ptr=ptr->next)
{
printf("\n%d %s %s",ptr->rollno,ptr->name,ptr->course);
}
printf("\nPress any key to continue...");
getch();
}

void search()
{
int r; struct student *ptr;
int found=0;
printf("Enter roll no to search : ");
scanf("%d",&r);
for(ptr=first;ptr!=NULL;ptr=ptr->next)
{
if(ptr->rollno==r)
{
found=1;
break;
}
}
if(found)
printf("Record Found");
else
printf("Record not found");

printf("\nPress any key to continue...");


getch();

}
void update()
{
}

void del()
{
int r; struct student *p1,*p2;
int found=0;
printf("Enter roll no to delete : ");
scanf("%d",&r);
if(first->rollno==r)
{
p1=first;
first=first->next;
free(p1);
found=1;
}
else if(last->rollno==r)
{
for(p1=first;p1->next!=last;p1=p1->next);
last=p1;
p1=p1->next;
free(p1);
last->next=NULL;
found=1;
}
else
{
for(p1=first,p2=p1->next;p2->next!=NULL;p1=p1->next,p2=p2-
>next)
{
if(p2->rollno==r)
{
p1->next=p2->next;
free(p2);
found=1;
break;
}
}
}

if(found)
printf("Record Deleted");
else
printf("Record Not found");

printf("\nPress any key to continue...");


getch();
}

int main()
{
int choice;
first=last=NULL;
for(;;)
{
printf("\n1: Add Record\n");
printf("\n2: Show Records\n");
printf("\n3: Search\n");
printf("\n4: Update\n");
printf("\n5: Delete\n");
printf("\n6: Exit\n");
printf("\n\nEnter choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1: add();break;
case 2: show();break;
case 3: search();break;
case 4: update();break;
case 5: del();break;
case 6: exit(0);
}
}

Double Linked List

To manage the addresses of previous and next nodes within the record

#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[31];
char course[15];
struct student *next,*prev;
};

struct student *first,*last;

void add()
{
struct student *temp=(struct student *)malloc(sizeof(struct student));
printf("Roll No : ");scanf("%d",&temp->rollno);
printf("Name : ");fflush(stdin);gets(temp->name);
printf("Course : ");fflush(stdin);gets(temp->course);
temp->next=NULL;
temp->prev=NULL;
if(first==NULL)
first=last=temp;
else
{
last->next=temp;
temp->prev=last;
last=temp;
}
printf("\nRecord Added...");
getch();
}
void show()
{
struct student *ptr;
for(ptr=first;ptr!=NULL;ptr=ptr->next)
{
printf("\n%d %s %s",ptr->rollno,ptr->name,ptr->course);
}
printf("\nPress any key to continue...");
getch();
}

void search()
{
int r; struct student *ptr;
int found=0;
printf("Enter roll no to search : ");
scanf("%d",&r);
for(ptr=first;ptr!=NULL;ptr=ptr->next)
{
if(ptr->rollno==r)
{
found=1;
break;
}
}
if(found)
printf("Record Found");
else
printf("Record not found");

printf("\nPress any key to continue...");


getch();

}
void update()
{
}

void del()
{
int r; struct student *ptr;
int found=0;
printf("Enter roll no to delete : ");
scanf("%d",&r);
if(first->rollno==r)
{
ptr=first;
first=first->next;
first->prev=NULL;
free(ptr);
found=1;
}
else if(last->rollno==r)
{
ptr=last;
last=last->prev;
last->next=NULL;
free(ptr);
found=1;
}
else
{
for(ptr=first->next;ptr!=NULL;ptr=ptr->next)
{
if(ptr->rollno==r)
{
ptr->prev->next=ptr->next;
ptr->next->prev=ptr->prev;
free(ptr);
found=1;
break;
}
}

if(found)
printf("Record Deleted");
else
printf("Record Not found");

printf("\nPress any key to continue...");


getch();
}

int main()
{
int choice;
first=last=NULL;
for(;;)
{
printf("\n1: Add Record\n");
printf("\n2: Show Records\n");
printf("\n3: Search\n");
printf("\n4: Update\n");
printf("\n5: Delete\n");
printf("\n6: Exit\n");
printf("\n\nEnter choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1: add();break;
case 2: show();break;
case 3: search();break;
case 4: update();break;
case 5: del();break;
case 6: exit(0);
}
}
}

Merging Files with Linked List


Queue

- A linear data structure based on First-in-First-out (FIFO)


- Nodes get added from rear side and removed from front side
- It is based on single linked list

Operations Allowed
1. Addition from rear side
2. Deletion from front side
3. Traversing
4. Search
5. Update

#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[31];
char course[15];
struct student *next;
};

struct student *front,*rear;

void add()
{
struct student *temp=(struct student *)malloc(sizeof(struct student));
printf("Roll No : ");scanf("%d",&temp->rollno);
printf("Name : ");fflush(stdin);gets(temp->name);
printf("Course : ");fflush(stdin);gets(temp->course);
temp->next=NULL;
if(front==NULL)
front=rear=temp;
else
{
rear->next=temp;
rear=temp;
}
printf("\nRecord Added...");
getch();
}
void show()
{
struct student *ptr;
for(ptr=front;ptr!=NULL;ptr=ptr->next)
{
printf("\n%d %s %s",ptr->rollno,ptr->name,ptr->course);
}
printf("\nPress any key to continue...");
getch();
}

void search()
{
int r; struct student *ptr;
int found=0;
printf("Enter roll no to search : ");
scanf("%d",&r);
for(ptr=front;ptr!=NULL;ptr=ptr->next)
{
if(ptr->rollno==r)
{
found=1;
break;
}
}
if(found)
printf("Record Found");
else
printf("Record not found");

printf("\nPress any key to continue...");


getch();

}
void update()
{
}

void del()
{
int r; struct student *ptr;
if(front!=NULL)
{
ptr=front;
front=front->next;
free(ptr);
printf("Node Deleted");
}
else
printf("No record in queue");

printf("\nPress any key to continue...");


getch();
}

int main()
{
int choice;
front=rear=NULL;
for(;;)
{
printf("\n1: Add Record\n");
printf("\n2: Show Records\n");
printf("\n3: Search\n");
printf("\n4: Update\n");
printf("\n5: Delete\n");
printf("\n6: Exit\n");
printf("\n\nEnter choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1: add();break;
case 2: show();break;
case 3: search();break;
case 4: update();break;
case 5: del();break;
case 6: exit(0);
}
}

}
Stack

A linear data structure to manage records in LIFO (Last-in-first-out)

- Items get added from top and removed from top


- It provides three operations
o Push
o Pop
o Peek
- Push means add the new node
- Pop means read and remove the topmost node
- Peek means read the topmost node but don’t delete it
- Check for overflow and underflow
- To check the overflow, check the returned address of malloc() or
calloc(). If it is NULL then more memory is available to allocate, which
gives an overflow.
- To check the underflow, check for the top most pointer. If it is NULL
then no record is found.

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int num;
struct node *next;
};
struct node *top;
void push()
{
struct node *temp=(struct node *) malloc(sizeof(struct node));
printf("Enter data in node : ");
scanf("%d",&temp->num);
temp->next=NULL;

if(temp==NULL)
{
printf("Sorry! No more memory to allocate. Overflow Occured");
return;
}
if(top==NULL)
top=temp;
else
{
temp->next=top;
top=temp;
}
printf("\nNode Added... Press any key to continue...");
getch();
}
void pop()
{
struct node *ptr;
if(top==NULL)
{
printf("Sorry! No record in stack... Underflow occured");
return;
}
printf("Item Popped : %d",top->num);
ptr=top;
top=top->next;
free(ptr);
}
void peek()
{
if(top==NULL)
printf("Sorry! No record in stack... Underflow occured");
else
printf("Item Peeked : %d",top->num);
}
void main()
{
int choice;
top=NULL;
for(;;)
{
printf("\n1: Push\n");
printf("2: Pop\n");
printf("3: Peek\n");
printf("4: Exit\n");
printf("\n\nEnter choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1: push();break;
case 2: pop();break;
case 3: peek();break;
case 4: exit(0);
default: printf("Wrong Choice");

}
}
}

Next Issues
Union
Enumerators
Bitfields

What is Union?

A user defined data type very similar to structure but contains less memory
space.
It holds only one element at a time. It allocates memory for biggest element
in the union and all other elements share the same memory space.

It is mainly used to better utilize memory.

Can never be used to create linked list, stack queue etc.

Example
For given program
#include<conio.h>
#include<stdio.h>
union test
{
char ch;
int num;
};
int main()
{
union test t;
t.num=590;
printf("%d",t.ch);
getch();
}

Output is
78

Comparison of Union and Structures


#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[51];
char address[100];
};
struct employee
{
int empid;
char name[51],mobile[11],email[100],addess[100];
};
union data
{
struct student s;
struct employee e;
};
struct student s;
struct employee e;
union data d;
void main()
{
int size=sizeof(s)+sizeof(e);
printf("size used in structures is : %d",size);//424
printf("\nsize used in union is : %d",sizeof(d));//268
getch();
}

Enumerators

- A user defined type to give names to the values


- Use enum keyword to define the enumerated names
- By default value starts with 0 and auto incremented by 1
enum {FALSE,TRUE};

int found=FALSE;

enum {admin=1,manager,student};

Example
#include<stdio.h>
#include<conio.h>
enum {admin=1,manager,student};
void main()
{
int choice;
printf("Who are you (1: Admin,2:Manager, 3: Student ? ");
scanf("%d",&choice);
switch(choice)
{
case admin:printf("Welcome Administrator"); break;
case manager:printf("Welcome all managers");break;
case student:printf("Dear Students join us");break;
}
getch();
}

- All enumerators are int type

Bitfields

- A method which allows to store data in bits rather than bytes


- Used with structures to declare elements with unsigned data type and
numbers of bits taken by a field

struct employee
{
unsigned empid:5;
unsigned gender:1;
unsigned indian:1;
unsigned type:1;
};

Here size of structure is only 1 byte.


struct employee
{
unsigned empid:5;
unsigned gender:1;
unsigned indian:1;
unsigned type:1;
unsigned mstatus:1;
};

Here size of structure is only 2 byte.

Example
#include<conio.h>
#include<stdio.h>
struct employee
{
unsigned empid:5;
unsigned gender:1;
unsigned indian:1;
unsigned type:1;
};

void main()
{
printf("size of structure is : %d",sizeof(struct employee));
getch();
}

Pointer Arithmetic

Since pointer hold the address, we can apply arithmetic operators on


pointers.
++ mean next address.
-- means previous address.

Case 1
WAP to get a string and show length of string using pointer arithmetic.

void main()
{
char *name; int len=0;
printf("Enter a name : ");
gets(name);
while(*name++ !='\0')
{
len++;
}
printf("Length is %d",len);
}

Function Pointers

- We can get address of a function as well and allows to run a method


indirectly
- A pointer that holds address of function is called as function pointer
- Same pointer can hold address of all functions
- A function pointer can hold address of defined type of function based
on syntax
- It is a kind of delegation to execute a function by a pointer

For Example

void (*fp)(int,int)
Here fp a pointer that can hold address of some function that takes two int
type argument and do not return any value.

Test Case: Write a program to get execute a method on demand using a


function pointer

#include<stdio.h>
#include<conio.h>
void sum(int a, int b)
{
printf("Sum is %d",a+b);
}
void product(int a, int b)
{
printf("Product is %d",a*b);
}
void fptr(int x, int y, void (*fp)(int,int))
{
/* fp is a function pointer that can invoke any function that takes
two arguments of int type and do not return anything
*/
fp(x,y);
}
int main()
{
int x, y,choice;
printf("Enter two numbers : ");
scanf("%d%d",&x,&y);
printf("What to do 1 : Sum 2 : Product");
printf("\n\nEnter choice : ");
scanf("%d",&choice);
if(choice==1)
fptr(x,y,&sum);
else
fptr(x,y,&product);
getch();
}

Difference between typedef and macro

- typedef can redefine an exiting type with new name while macro can
redefine an new or exiting type as well

#define int char (valid)


typedef int char; (wrong)

Conditional Compilation

- A method to compile the code only we define and create a limited


version of executable files
- Some special pre-processor directives are used
o #if
o #ifdef
o #else
o #elseif
o #endif
#define DEMO
void main()
{
clrscr();
#ifdef DEMO
printf("This is a demo version");
#else
printf("This is full version");
#endif
}

void pointer or Generic Pointers

- A pointer that can hold address of any type


o void *ptr;
- While doing operation we need to cast the pointer to define the size on
which it has to operate
Example

int num=6;
double k=6.9;

ptr=&num;
*(int *)ptr=20;

ptr=&k;
*(double *)ptr=2.3;

Fetching Environmental Variables

- An environmental variable is the information managed by the


operating system
- To view all environmental variables in your system use SET command
on command prompt

//Reading all environmental variables


#include<stdio.h>
void main(int argc, char *argv[], char *env[])
{
clrscr();
while(*env++!=NULL)
{
printf("%s\n",*env);
}
}

Using Linux on Windows

- Use Virtual Memory Managers like VMWare

Das könnte Ihnen auch gefallen