PL_CS
PL_CS
PL_CS
CS-103
Programming Languages
(FD)
Name : _____________________________
Year : _____________________________
Batch : _____________________________
Roll No : _____________________________
Department: _____________________________
Teacher : _____________________________
The Practical Workbook for “Programming Languages” introduces the basic as well as advance
concepts of programming using C language. C has been selected for this purpose because it
encompasses the characteristics of both the high level languages; which give a better
programming efficiency and faster program development; and the low level languages; which
have a better machine efficiency.
Each lab session begins with a brief theory of the topic. Many details have not been incorporated
as the same is to be covered in Theory classes. The Exercise section follows this section.
The Workbook has been arranged as thirty labs starting with a practical on the Introduction to
programming environment and fundamentals of programming language.
Next lab session deals with single stepping; an efficient debugging and error detection technique.
Next three lab sessions cover the basic building blocks of programming. These practicals
introduce the concepts of decision making; loops; function declaration and definition etc.
The next three experiments deal with the advance concepts like arrays, pointers, structures and
unions. These features enable the users to handle not only large amount of data, but also data of
different types (integers, characters etc.) and to do so efficiently.
Separate practicals have been included for different graphics and text modes, passing variable
number of arguments to functions, and command line arguments.
Further two lab sessions covers the filing feature, which allows the user to store/retrieve the data
on/from permanent storage like floppy or hard disk and various file and directory manipulation
functions.
Finally, there are labs on hardware interfacing using ROM BIOS routines, which explain
accessing the system color palettes, interfacing mouse etc. in programs using C.
Few changes have been made in the examples and exercises of this workbook since its last
edition which was printed in 2011. Now these are more comprehensive than those of the
previous issue. One lab session of the previous workbook is replaced by an appendix that
discusses various date and time functions.
Practical Workbook
Programming Languages
CONTENTS
Lab Session Page
Objective
No. No.
1 Programming Environment Setup Using Turbo C Compiler 1
2 Fundamentals of Programming Language 4
3 Debugging and Single-Stepping of Programs 8
4 Installing Breakpoints for Debugging 11
5 Decision Making in Programming (If, If-else) 13
6 Decision Making in Programming (Switch Case, Ternary Operator) 16
7 Study of Loops ( For loop) 19
8 Study of Loops (While, do-while loop) 22
9 Break and Continue 25
10 Study of Functions 28
11 Recursion 33
12 Study of Arrays 35
13 String Arrays 39
14 Study of Structures 42
15 Unions 44
16 Graphics in C 46
17 Executing Different Functions in Graphics 48
18 Study of Pointer Variables 52
19 Pointers and Arrays 55
20 Pointers as Function Arguments 58
21 Working with Files 61
22 Linked List 65
23 File and Directory Manipulation Functions 68
24 Command Line Arguments 71
25 Variable Length Arguments 74
26 Hardware Interfacing through User-developed Programs 81
27 Parallel Port Interfacing 85
28 Mouse Interfacing using Programs in C-Language 87
29 Type and Storage Classes 91
30 Project 94
Programming Languages Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 01
OBJECTIVE
Familiarization with Programming Environment using Turbo C
THEORY
The Development Environment - Integrated Development Environment (IDE):
The C compiler has its own built-in text editor. You may also use a commercial text editor or
word processor that can produce text files. The important thing is that whatever you write
your program in, it must save simple, plain-text files, with no word processing commands
embedded in the text. The files you create with your editor are called source files, and for
C++ they typically are named with the extension .CPP, .CP, or .C.
To do so from the command prompt go in the specific directory and type ‘tc’. This makes you
enter the IDE interface, which initially displays only a menu bar at the top of the screen and a
status line below will appear. The menu bar displays the menu names and the status line tells
what various function keys will do.
Using Menus
If the menu bar is inactive, it may be invoked by pressing the [F10] function key. To select
different menu, move the highlight left or right with cursor (arrow) keys. You can also revoke
the selection by pressing the key combination for the specific menu.
Writing a Program
When the Edit window is active, the program may be typed. Use the certain key
combinations to perform specific edit functions.
Saving a Program
To save the program, select save command from the file menu. This function can also be
performed by pressing the [F2] button. A dialog box will appear asking for the path and name
of the file. Provide an appropriate and unique file name. You can save the program after
compiling too but saving it before compilation is more appropriate.
1
Programming Languages Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
The source file is required to be turned into an executable file. This is called “Making” of the
.exe file. The steps required to create an executable file are:
1. Create a source file, with a .cpp extension.
2. Compile the source code into a file with the .obj extension.
3. Link your .obj file with any needed libraries to produce an executable program.
Project/Make
Before compiling and linking a file, a part of the IDE called Project/Make checks the time
and date on the file you are going to compile.
Executing a Program
If the program is compiled and linked without errors, the program is executed by selecting
Run from the Run Menu or by pressing the [Ctrl+F9] key combination.
Correcting Errors
If the compiler recognizes some error, it will let you know through the Compiler window.
You’ll see that the number of errors is not listed as 0, and the word “Error” appears instead of
the word “Success” at the bottom of the window. The errors are to be removed by returning
to the edit window. Usually these errors are a result of a typing mistake. The compiler will
not only tell you what you did wrong; they’ll point you to the exact place in your code where
you made the mistake.
2
Programming Languages Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Exiting IDE
An Edit window may be closed in a number of different ways. You can click on the small
square in the upper left corner, you can select close from the window menu, or you can press
the [Alt][F3] combination. To exit from the IDE select Exit from the File menu or press
[Alt][X] combination.
EXERCISES
1. Load and execute the following program using Turbo C environment. Explore
different features available for execution.
#include<stdio.h>
int main()
{
Print (“Hello World \n”)
Return 0
}
3
Programming Languages Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 02
OBJECTIVE
Fundamentals of Programming Language
Operators
There are various types of operators that may be placed in three categories:
Basic: + - * / %
Assignment: = += -= *= /= %=
(++, -- may also be considered as assignment operators)
Relational: < > <= >= == !=
Format Specifiers
Format Specifiers tell the printf statement where to put the text and how to display the text.
The various format specifiers are:
%d => integer
%c => character
%f => floating point etc.
Escape Sequences
Escape Sequence causes the program to escape from the normal interpretation of a string, so
that the next character is recognized as having a special meaning. The back slash “\”
character is called the Escape Character”. The escape sequence includes the following:
\n => new line
\b => back space
\r => carriage return
\” => double quotations
\\ => back slash etc.
4
Programming Languages Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Examples
#include<conio.h>
#include<stdio.h>
void main(void)
{
clrscr();
printf(“\n Hello World”);
getch();
}
#include<conio.h>
#include<stdio.h>
void main(void)
{
clrscr();
int num1,num2,sum,product;
printf(“\tThe program takes two numbers as input and
prints their sum and product”);
printf(“\n Enter first number:”);
scanf(“%d”,&num1);
printf(“\n Enter second number:”);
scanf(“%d”,&num2);
sum=num1+num2;
product=num1*num2;
printf(“\n%d+%d=%d”,num1,num2,sum);
printf(“\n%d*%d=%d”,num1,num2,product);
getch();
}
EXERCISES
1. Type the following program in C Editor and execute it. Mention the Error (if any).
void main(void)
{
printf(“This is my first program in C”);
}
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
5
Programming Languages Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Add the following line at the beginning of the above program. Recompile the
program. What is the output?
#include<stdio.h>
___________________________________________________________________________
___________________________________________________________________________
3. Make the following changes to the program. Mention the Errors observed, in your
own words:
i. Write Void instead of void.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
4. Write a program to calculate the Area (A= 𝜋r2) and circumference of a circle (C=2πr),
where r = radius is taken as input and 𝜋 is declared as a constant. The precision of 𝜋
should be the number of characters in your name. Display the result to 4 decimal
places.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________
6
Programming Languages Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
7
Programming Languages Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 03
OBJECTIVE
Debugging and Single-Stepping of Programs
THEORY
One of the most innovative and useful features of Turbo C++ is the integration of debugging
facilities into the IDE.
Even if your program compiles perfectly, it still may not work. Such errors that cause the
program to give incorrect results are called Logical Errors. The first thing that should be
done is to review the listing carefully. Often, the mistake will be obvious. But, if it is not,
you’ll need the assistance of the Turbo C Debugger.
Our intention in this program is that when number is between 0 and 100, answer will be 1,
when the number is 100 or greater, answer will be 0, and when number is less than 0,
answer will retain its initialized value of –1. When we run this program with a test value of
-50 for number, we find that answer is set to 0 at the end of the program, instead of staying
–1.
We can understand where the problem is if we single step through the program. To do this,
simply press the [F7] key. The first line of the program will be highlighted. This highlighted
line is called the run bar. Press [F7] again. The run bar will move to the next program line.
The run bar appears on the line about to be executed. You can execute each line of the
program in turn by pressing [F7]. Eventually you’ll reach the first if statement:
8
Programming Languages Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
This statement is true (since number is –50); so, as we would expect the run bar moves to the
second if statement:
This is false. Because there’s no else matched with the second if, we would expect the run bar
to the printf( ) statement. But it doesn’t! It goes to the line
answer = 0;
Now that we see where the program actually goes, the source of the bug should become clear.
The else goes with the last if, not the first if as the indenting would lead us to believe. So, the
else is executed when the second if statement is false, which leads to erroneous results. We
need to put braces around the second if, or rewrite the program in some other way.
Watches
Single stepping is usually used with other features of the debugger. The most useful of these
is the watch (or watch expression). This lets you see how the value of variable changes as the
program runs. To add a watch expression, press [Ctrl+F7] and type the expression.
EXERCISES
1. Fill out all the entities in table by their corresponding values by inserting watches and
single stepping the program.
sqr= num*num ;
ch ++;
9
Programming Languages Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Before
After Execution
Execution
x y avg x y avg
iii. int x=your_roll_no,y=your_roll_no+50;
float avg;
avg=(x+y)/2;
10
Programming Languages Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 04
OBJECTIVE
Installing Breakpoints for Debugging
Breakpoints
It often happens that you’ve debugged part of your program, but must deal with a bug in
another section, and you don’t want to single-step through all the statements in the first part to
get to the section with the bug. Or you may have a loop with many iterations that would be
tedious to step through. The way to do this is with a breakpoint. A breakpoint marks a
statement where the program will stop. If you start the program with [Ctrl][F9], it will execute
all the statements up to the breakpoint, then stop. You can now examine the state of the
variables at that point using the watch window.
Installing breakpoints
To set a breakpoint, first position the cursor on the appropriate line. Then select Toggle
Breakpoint from the Debug menu (or press [Ctrl][F8]). The line with the breakpoint will be
highlighted. You can install as many breakpoints as you want. This is useful if the program
can take several different paths, depending on the result of if statements or other branching
constructs.
Removing Breakpoints
You can remove a single breakpoint by positioning the cursor on the line with the breakpoint
and selecting Toggle breakpoint from the Debug menu or pressing the [Ctrl][F8] combination
(just as you did to install the breakpoint). The breakpoint highlight will vanish.
You can all set Conditional Breakpoints that would break at the specified value only.
EXERCISES
1. The programs given below contain some syntax and/or logical error(s). By debugging
and installing breakpoints, mention the error(s) along with their categorization into
syntactical or logical error. Also, write the correct program statements.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
11
Programming Languages Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
if (x=2010)
printf(“Your batch is 2010”)
else
printf(“Your batch is %d”,x);
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
iii. // To calculate the number of characters entered by the user. Exit on Esc or Enter.
int count=0;
char ch;
while(ch=getche( )!=27)
{
if(Ch=='\r');
break;
count++;
}
printf("Count =%d",count);
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
12
Programming Languages Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 05
OBJECTIVE
Decision Making in Programming (If, If-else)
THEORY
Normally, your program flows along line by line in the order in which it appears in your
source code. But, it is sometimes required to execute a particular portion of code only if
certain condition is true; or false i.e. you have to make decision in your program. There are
three major decision making structures. Four decision making structures:
1. If statement
2. If-else statement
3. Switch case
4. Conditional Operator (Rarely used)
The if statement
The if statement enables you to test for a condition (such as whether two variables are equal)
and branch to different parts of your code, depending on the result.
The simplest form of an if statement is:
if (expression)
statement;
The expression may consist of logical or relational operators like (> >= < <= && || )
void main(void)
{
int var;
printf(“Enter any number;”);
scanf(“%d”,&var);
if(var==10)
printf(“The user entered number is Ten”);
}
if (expression)
statement;
else
statement;
13
Programming Languages Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Note: To execute multiple statements when a condition is true or false, parentheses are used.
Consider the following example that checks whether the input character is an upper case or
lower case:
void main(void)
{
char ch;
printf(“Enter any character”);
ch=getche();
if(ch>=’A’&&ch<=’Z’)
printf(“%c is an upper case character”,ch);
else
printf(“%c is a lower case character”,ch);
getch();
}
Typecasting
Typecasting allow a variable of one type to act like another for a single operation. In C
typecasting is performed by placing, in front of the value, the type name in parentheses.
EXERCISES
1. Write a program that takes a number as input from user and checks whether the
number is even or odd using if-else.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
#include<stdio.h>
void main()
{
int a=100;
if(a>10)
printf("Shahid Afridi");
else if(a>20)
14
Programming Languages Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
printf("Shoaib Akhtar");
else if(a>30)
printf("Kamran Akmal");
}
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
15
Programming Languages Lab Session 06
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 06
OBJECTIVE
Decision Making in Programming (Switch Case, Ternary Operator)
THEORY
The switch Statement
Unlike if, which evaluates one value, switch statements allow you to branch on any of a
number of different values. The general form of the switch statement is:
switch (expression)
{
case valueOne: statement;
break;
case valueTwo: statement;
break;
....
case valueN: statement;
break;
default: statement;
}
An Example:
void main(void)
{
clrscr();
char grade;
printf(“\n Enter your Grade: ”);
grade=getche();
switch(grade)
{
case ‘A’:
case ‘a’:
printf(“\n Your percentage is 80 or above 80 ”);
break;
case ‘B’:
case ‘b’:
printf(“\n Your percentage is in 70-80 ”);
break;
default:
printf(“\n Your percentage is below 70 ”);
}
getch();
}
16
Programming Languages Lab Session 06
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
The conditional operator (? :) is C’s only ternary operator; that is, it is the only operator to
take three terms.
This line is read as "If expression1 is true, return the value of expression2; otherwise, return
the value of expression3." Typically, this value would be assigned to a variable.
An Example:
void main(void)
{
clrscr();
float per;
printf(“\n Enter your percentage;”);
scanf(“%f”,&per);
printf(“\n you are”);
printf(“%s”, per >= 60 ?“Passed”:”Failed”);
getch();
}
EXERCISES
1. Write a program that takes a number as input from user and checks whether the
number is even or odd.
a) Switch case:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
17
Programming Languages Lab Session 06
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
2. Write a program that declares and initializes two numbers with your_roll_no and
your_friend_roll_no and displays the greater of the two. Use ternary operator.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
18
Programming Languages Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 07
OBJECTIVE
Study of Loops ( For loop)
THEORY
Types of Loops
void main(void)
{
clrscr();
for(int i=1;i<100;i+=2)
printf(“%d\t”,i);
}
EXERCISES
1. Write necessary statements using for loop for the following:
___________________________________________________________________________
___________________________________________________________________________
19
Programming Languages Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
ii. To print all the odd numbers between Your_roll_no and Your_roll_no + 100.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
iii. To print the square of number(s) repeatedly till the 1 is entered by user..
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
20
Programming Languages Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
1 10 2 9 3 8 4 7 5 6 6 5 7 4 8 3 9 2 10 1
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
21
Programming Languages Lab Session 09
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 08
OBJECTIVE
Study of Loops (While, do-while loop)
An Example: A program that prints all numbers from 1 to 100 those are divisible by 5
void main(void)
{
clrscr();
int i;
while(i<=100)
{
if(i%5==0)
printf(“\t\n %d ”,i);
i++;
}//while ends
}//main ends
This loop runs as long as the condition in the parenthesis is true. Note that there is a
semicolon after the “while” statement. The difference between the “while” and the “do-
while” statements is that in the “while” loop the test condition is evaluated before the loop is
executed, while in the “do” loop the test condition is evaluated after the loop is executed. This
implies that statements in a “do” loop are executed at least once. However, the statements in
the “while” loop are not necessarily executed.
void main(void)
{
clrscr();
22
Programming Languages Lab Session 09
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
int i=0;
do
{
printf(“\n\t Your Name”);
i++;
}
while(i<10);
}//main ends
EXERCISES
1. Write necessary statements using for loop for the following:
___________________________________________________________________________
___________________________________________________________________________
ii. To print all the odd numbers between Your_roll_no and Your_roll_no + 100.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
iv. To print the square of number(s) repeatedly till the 1 is entered by user..
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
23
Programming Languages Lab Session 09
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
3. Write a program to print the average of two numbers input by user using while loop.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
1 10 2 9 3 8 4 7 5 6 6 5 7 4 8 3 9 2 10 1
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
24
Programming Languages Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 09
OBJECTIVE
Using Break and Continue within loops
THEORY
Two keywords that are very important to looping are break and continue. The break command
will exit the most immediately surrounding loop regardless of what the conditions of the loop
are. Break is useful if we want to exit a loop under special circumstances. For example, let's
say the program we're working on is a two-person checkers game. The basic structure of the
program might look like this:
while (true)
{
take_turn(player1);
take_turn(player2);
}
This will make the game alternate between having player 1 and player 2 take turns. The only
problem with this logic is that there's no way to exit the game; the loop will run forever.
Following example shows a different approach
while(true)
{
if (someone_has_won() || someone_wants_to_quit() == TRUE)
{
break;
}
take_turn(player1);
if (someone_has_won() || someone_wants_to_quit() == TRUE)
{
break;
}
take_turn(player2);
}
This code accomplishes what we want--the primary loop of the game will continue under
normal circumstances, but under a special condition (winning or exiting) the flow will stop
and our program will do something else.
25
Programming Languages Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Continue is another keyword that controls the flow of loops. If you are executing a loop and
hit a continue statement, the loop will stop its current iteration, update itself (in the case of for
loops) and begin to execute again from the top. Essentially, the continue statement is saying
"this iteration of the loop is done, let's continue with the loop without executing whatever
code comes after me." Let's say we're implementing a game of Monopoly. Like above, we
want to use a loop to control whose turn it is, but controlling turns is a bit more complicated
in Monopoly than in checkers. The basic structure of our code might then look something like
this:
Exercise:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
26
Programming Languages Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
27
Programming Languages Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 10
OBJECTIVE
Study of Functions
THEORY
Types of functions in C programming
Depending on whether a function is defined by the user or already included in C
compilers, there are two types of functions in C programming
There are two types of functions in C programming:
Standard library functions
User defined functions
Standard library functions
The printf() is a standard library function to send formatted output to the screen
(display output on the screen). This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all
these functions are available for use.
User-defined functions
#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}
int main()
{
28
Programming Languages Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
The execution of a C program begins from the main() function.When the compiler
encounters functionName(); inside the main function, control of the progr am jumps
to
void functionName()
And, the compiler starts executing the codes inside the user -defined function.The
control of the program jumps to statement next to functionName();once all the
codes inside the function definition are executed. Before defining a function, it is
required to declare the function i.e. to specify the function prototype. A function declaration is
followed by a semicolon ‘;’. Unlike the function definition only data type are to be mentioned
for arguments in the function declaration. The function call is made as follows:
return_type = function_name(arguments);
There are four types of functions depending on the return type and arguments:
Functions that take nothing as argument and return nothing.
Functions that take arguments but return nothing.
Functions that do not take arguments but return something.
Functions that take arguments and return something.
29
Programming Languages Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Consider another example that adds two numbers using a function sum() .
void sum(void);
void main(void)
{
printf(“\nProgram to print sum of two numbers\n”);
sum(void);
}
void sum(void)
{
int num1,num2,sum;
printf(“Enter 1st number:”);
scanf(“%d”,&num1);
printf(“Enter 2nd number:”);
scanf(“%d”,&num2);
sum=num1+num2;
printf(“Sum of %d+%d=%d”,num1,num2,sum);
}
EXERCISES
1. Using function, write a complete program that prints your name 10 times. The
function can take no arguments and should not return any value.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
2. Write function definition that takes two complex numbers as argument and prints their
sum.
___________________________________________________________________________
30
Programming Languages Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
3. Using a function, swap the values of two variables. The function takes two values of
Variables as arguments and returns the swapped values:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
31
Programming Languages Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
b) #include<stdio.h>
int main()
{
int myfunc(int);
int b;
b=myfunc(20);
printf(“%d”,b);
return 0;
}
int myfunc(int a)
{
a > 20? return(10): return(20);
}
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
32
Programming Languages Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 11
OBJECTIVE
Recursion
Theory
Recursion is an ability of a function to call itself.
int add(int);
void main(void)
{
int num,ans;
printf(“Enter any number:”);
scanf(“%d”,&num);
ans=add(num);
printf(“Answer=%d”,ans);
getch();
}
int add(int n)
{
int result;
if(n==1)
return 1;
result=add(n-1) + n;
return result;
}
Built-in Functions
There are various header files which contain built-in functions. The programmer can include
those header files in any program and then use the built-in function by just calling them.
EXERCISES
1. Using recursion, write a program that takes a number as input and print its binary
equivalent.
___________________________________________________________________________
___________________________________________________________________________
33
Programming Languages Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
2. main( ) is a function. Write a function which calls main( ). What is the output of this
program?
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
34
Programming Languages Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 12
OBJECTIVE
Study of Arrays
THEORY
An array is a collection of data storage locations, each of which holds the same type of data.
Each storage location is called an element of the array. You declare an array by writing the
type, followed by the array name and the subscript. The subscript is the number of elements in
the array, surrounded by square brackets. For example,
long LongArray[25];
declares an array of 25 long integers, named LongArray. When the compiler sees this
declaration, it sets aside enough memory to hold all 25 elements. Because each long integer
requires 4 bytes, this declaration sets aside 100 contiguous bytes of memory.
Consider the following program that take 10 numbers as input in an array and then print that
array.
#include<stdio.h>
void main(void)
clrscr();
int arr[10];
for(int i=0;i<10;i++)
scanf(“%d”,&arr[i]);
clrscr();
35
Programming Languages Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
for(int j=0;j<10;j++)
getch();
EXERCISES
1. Write a program that store first n Fibonacci numbers in an array, where n is equal to
your_roll_no.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
3. Declare an array of length equal to Your_roll_no. Take input in the array using a
function. Use another function to find the smallest element in that array.
___________________________________________________________________________
36
Programming Languages Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
37
Programming Languages Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
38
Programming Languages Lab Session 15
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 13
OBJECTIVE
String Arrays
THEORY
A string is an especial type of array of type char. Strings are the form of data used in
programming languages for storing and manipulating text. A string is a one dimensional array of
characters. Following are some examples of string
initializations
char str1[]={ N , E , D , \0 };
char str2[]={ NED };
char str3[]= NED ;
Each character in the string occupies one byte of memory and the last character is always
a NULL i.e. \0 , which indicates that the string has terminated. Note that in the second
and third statements of initialization \0 is not necessary. C inserts the NULL character
automatically.
An example
Let us consider an example in which a user provides a string (character by character) and
then the stored string is displayed on the screen.
/* Strings*/
void main(void)
{
clrscr();
char str[20];
char ch;
int i=0;
printf( \nEnter a string (20-characters max): );
while((ch=getche())!= \r ) /*Input characters until
return key is hit*/
{
str[i]=ch;
i++;
}
str[i] = \0 ;
printf( \nThe stored string is %s ,str);
getch();
}
It is necessary to provide \0 character in the end. For instance if you make
that statement a comment, you will observe erroneous results on the screen.
There are many library functions for string handling in C. Some of the most common are
39
Programming Languages Lab Session 15
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
listed below. In order to use these library functions you have to include header file
named string.h.
Functions Use
EXERCISES
1. Implement the built-in function strcmpi() present in header file “string.h”
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
2. Write a program that takes five names as input and sort them by their lengths. Use a
separate function for sorting.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
40
Programming Languages Lab Session 15
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
41
Programming Languages Lab Session 15
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 14
OBJECTIVE
Study of Structures
THEORY
If we want a group of same data type we use an array. If we want a group of elements of
different data types we use structures. For Example: To store the names, prices and number of
pages of a book you can declare three variables. To store this information for more than one
book three separate arrays may be declared. Another option is to make a structure. No
memory is allocated when a structure is declared. It simply defines the “form” of the
structure. When a variable is made then memory is allocated. This is equivalent to saying that
there is no memory for “int”, but when we declare an integer i.e. int var; only then memory
is allocated.
struct personnel
{
char name[50];
int agentno;
};
void main(void)
{
printf(“%s”,agent1.name);
printf(“%d”,agent1.agentno);
getch();
EXERCISES
1. Declare a structure named employee that stores the employee id, salary and
department.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
42
Programming Languages Lab Session 15
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
43
Programming Languages Lab Session 15
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 15
OBJECTIVE
Unions
THEORY
Unions are also used to group a number of different variables together like a structure. But,
unlike structures, union enables us to treat the same space in memory as a number of different
variables. That is, a union is a way for a section of memory to be treated as a variable of one
type on one occasion, and as a different variable, of a different type, on another occasion.
In a structure, all the members are individual objects allocated contiguously. In a union, all
the members refer to the same object, and are allocated at the same address. All the members
of a union are equivalent, and the size of a union will be the size of its largest member. An
example is shows as
union
{ char a; int b; long c; }
u = 1;
field a is initialized with the value 1 on a char. It is then more convenient to define the largest
field first to be sure to initialize all the union byte.
EXERCISES
1. Declare an array of 40 employees for the structure defined in question1. Also write
statements to assign the following values to the employee [6].
Employee id = “Your_roll_no” salary = 30,000 and department = “IT dept”
___________________________________________________________________________
___________________________________________________________________________
2. Write a function that prints the highest salaried person amongst the employees defined
in question 1.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
44
Programming Languages Lab Session 15
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
45
Programming Languages Lab Session 16
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 16
OBJECTIVE
Graphics in C
THEORY
There are two ways to view the display screen in Turbo C graphics model:
The Text Mode
The Graphics Mode.
All the ANSI codes start by the character \x1B[ after which, we mention codes specific to
certain operation. Using the #define directive will make the programs easier to write and
understand.
LIBRARY FUNCTIONS
initgraph():
This function initializes the graphics system by loading a graphics driver from disk (or
46
Programming Languages Lab Session 16
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
validating a registered driver) then putting the system into graphics mode. initgraph also
resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults,
then resets graphresult to 0.
Declaration:
void far initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);
*graphdriver:
Integer that specifies the graphics driver to be used. *graphmode : Integer that specifies the
initial graphics mode (unless *graphdriver =DETECT).
If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for
the detected driver.
pathtodriver : Specifies the directory path where initgraph looks for graphics drivers
*pathtodriver. Full pathname of directory, where the driver files reside. If the driver is not
found in the specified path, the function will search the current directory for the .BGI files.
closegraph():
This function switches back the screen from graphcs mode to text mode. It clears the
screen also. A graphics program should have a closegraph function at the end of graphics.
Otherwise DOS screen will not go to text mode after running the program. Here, closegraph()
is called after getch() since screen should not clear until user hits a key.
EXERCISES
___________________________________________________________________________
___________________________________________________________________________
2. Which header file is required to be included while working in (a) text mode (b)
graphics mode?
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
3. Name the functions used to clear the screen in (a) text mode (b) graphics mode
___________________________________________________________________________
___________________________________________________________________________
47
Programming Languages Lab Session 17
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 17
OBJECTIVE
Executing Different Functions in Graphics
THEORY
outtextxy():
Function outtextxy() displays a string in graphical mode. You can use different fonts, text sizes,
alignments, colors and directions of the text. Parameters passed are x and y coordinates of the
position on the screen where text is to be displayed.
Declaration:
void far outtextxy(int x, int y, char *text);
circle():
circle() function takes x & y coordinates of the center of the circle with respect to left top
of the screen and radius of the circle in terms of pixels as arguments.
Declaration:
void far circle(int x, int y, int radius);
(x,y): Center point circle. radius: Radius of circle.
To draw a border, rectangle and square use rectangle() in the current drawing color, line style
and thickness. To draw polygon with n sides specifying n+1 points, the first and the last point
being the same.
Declaration:
void far rectangle(int left, int top, int right, int bottom);
void far drawpoly(int numpoints, int far *polypoints);
(left,top) is the upper left corner of the rectangle, and (right,bottom) is its lower right corner.
numpoints: Specifies number of point.s
olypoints:
Points to a sequence of (numpoints x 2) integers. Each pair of integers gives the x and y
coordinates of a point on the polygon. To draw a closed polygon with N points, numpoints
should be N+1 and the array polypoints[] should contain 2(N+1) integers with first 2 integers
equal to last 2 integers.
Following is an example that displays different shapes in graphics mode (Circle, Rectangle and
Line etc.)
void main(void)
48
Programming Languages Lab Session 17
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
{
int gm,gd=DETECT;
initgraph(&gd,&gm,”path”);
circle(100,100,50);
outtextxy(75,170,”Circle”);
rectangle(200,50,350,150);
outtextxy(240,170,” Rectangle”);
line(100,250,540,250);
outtextxy(300,260,”Line”);
ellipse(500,100,0,360,100,50);
outtextxy(480,170,”Ellipse”);
getch();
closegraph();
}
EXERCISES
1. Write a program to draw a circle whose diameter should be equivalent to the width of the
screen and an ellipse whose center should be at center of screen.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
49
Programming Languages Lab Session 17
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
50
Programming Languages Lab Session 17
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
#include<conio.h>
void main()
{
int gd=DETECT, gm;
initgraph(&gd, &gm, "c:\\turboc3\\bgi " );
circle(200,100,150);
getch();
closegraph();
}
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________________________
51
Programming Languages Lab Session 19
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 18
OBJECTIVE
Study of Pointer Variables
THEORY
A pointer provides a way of accessing a variable without referring to the variable directly. The
address of the variable is used.
The declaration of the pointer ip,
int *ip;
means that the expression *ip is an int. This definition set aside two bytes in which to store the
address of an integer variable and gives this storage space the name ip. If instead of int we
declare
char * ip;
again, in this case 2 bytes will be occupied, but this time the address stored will be pointing to a
single byte.
EXERCISES
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
52
Programming Languages Lab Session 19
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
53
Programming Languages Lab Session 19
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
54
Programming Languages Lab Session 20
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 19
OBJECTIVE
There is an inherent relationship between arrays and pointers; in fact, the compiler
translates array notations into pointer notations when compiling the code, since the
internal architecture of the microprocessor does not understand arrays.An array name can be thought
of as a constant pointer. Pointer can be used to do any operation involving array subscript. Let us
look at a simple example.
An example:
EXERCISES
1. Write pointer notation equivalent to the following array notations:
a. arr[10] : _____________________________________
b. arr2D[5][6] : _____________________________________
2. Using dynamic memory allocation, declare an array of the length user wants. Take input
in that array and then print all those numbers, input by the user, which are even. The
verification of whether a number is even or not should be done via macro.
55
Programming Languages Lab Session 20
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
56
Programming Languages Lab Session 20
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
57
Programming Languages Lab Session 21
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 20
OBJECTIVE
Pointers as Function Arguments
THEORY
One of the best things about pointers is that they allow functions to alter variables outside of
their own scope. By passing a pointer to a function you can allow that function to read and
write to the data stored in that variable. Say you want to write a function that swaps the values of
two variables. Without pointers this would be practically impossible, following is an example
showing its application.
#include <stdio.h>
int
main()
{
int a = 4, b = 7;
swap_ints(&a, &b);
return 0;
}
int
swap_ints(int *first_number, int *second_number)
{
int temp;
return 0;
}
58
Programming Languages Lab Session 21
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXERCISES
1. Using pointers, write a program that takes a string as input from user and calculates the
number of vowels in it.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
59
Programming Languages Lab Session 21
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
60
Programming Languages Lab Session 22
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 21
OBJECTIVE
Working with Files
THEORY
A majority of programs need to read and write data to disk-based storage systems. This is to be
done to provide permanent storage of data. Disk I/O operations are performed on entities called
files A file is a collection of bytes that is given a name. The various ways file I/O can be
performed in C form a number of overlapping categories, which include Standard I/O and
System I/O.
When accessing files through C, the first necessity is to have a way to access the files. For C File
I/O you need to use a FILE pointer, which will let the program keep track of the file being
accessed. For Example:
FILE *fp;
To open a file you need to use the fopen function, which returns a FILE pointer. Once you've
opened a file, you can use the FILE pointer to let the compiler perform input and output
functions on the file.
Here filename is string literal which you will use to name your file and mode can have one of the
following values
61
Programming Languages Lab Session 22
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Data can be written to and read from the files in different ways using different functions. These
functions include:
Character IO
int getc(FILE *stream);
getc returns the next character on the given input stream and increments the stream's file pointer
to point to the next character.
String IO
char *fgets(char *s, int n, FILE *stream);
fgets reads characters from stream into the string s. It stops when it reads either n – 1 characters
or a newline character, whichever comes first. fgets retains the newline character at the end of s
and appends a null byte to s to mark the end of the string.
Formatted IO
int fscanf (FILE *stream,const char *format [,address,...]);
Scans and formats input from a stream
Record IO
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
fread reads a specified number of equal-sized data items from an input stream into a block.
EXERCISES
1. Write a program that takes input the names of the subjects from the user and write them
on to the file Subject.txt.
___________________________________________________________________________
62
Programming Languages Lab Session 22
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
2. Using formatted IO; write the information about a book onto a file which might be taken
as input from user. Book information includes its ISBN number, title and price.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
63
Programming Languages Lab Session 22
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
3. Write down necessary statements to open a file document.txt for reading and appending
in binary mode.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
64
Programming Languages Lab Session 22
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 22
OBJECTIVE
Linked List
THEORY
Form the term dynamic memory allocation, we mean that, the size of memory allocated for holding
data can grow as well as shrink, on the time of execution. This will effectively help in managing
memory since a predefined memory chunk can either be too large or insufficient. Linked list is one of
the way of obtaining dynamic data structures in which collection of data items (structures) are lined
up in a row and the insertion and deletion can be made any where in the list. Each member of the
linked list (node) is connected to another by a pointer which holds the address of the next node. The
pointer of the last node points to NULL, which means end of list. With the help of linked list we can
implement a complex data base system. following are some important building blocks and functions
used in dynamic memory allocation.
malloc( )
It takes as an argument the number of bytes to be allocated and on call, returns a pointer of type void
to the allocated memory. This pointer can be assigned to a variable of any pointer type. It is normally
used with sizeof operator.
free( )
The function free() deallocates memory. It takes as an argument the pointer to the
allocated memory which has to be freed.
free(ptr);
Let s explore some of the basic features of linked list from the following example. Here we have
implemented a small record holding program. It asks from the user about the employee s name and
his identification number. For that we have declared a stricture emp capable of holding above
mentioned fields along with the address of next node. The program has two user defined functions
creat() and lstal() to perform the functions of growing nodes and listing the data of all nodes
respectively.
#include<conio.h> #include<alloc.h>
#include<stdio.h> #include<dos.h>
#include<stdlib.h> struct emp
{
int perno;
char name[20];
65
Programming Languages Lab Session 22
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
66
Programming Languages Lab Session 22
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXERCISES
1. Write a program that could delete any node form the linked list. Also make use of
free( ) function.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
67
Programming Languages Lab Session 24
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 23
OBJECTIVE
File and Directory Manipulation Functions
THEORY
File Manipulation is a key task to be performed by C programs, because all applications and
data reside in files. If you develop an application, it is likely to use files for storage of its data
and results so that they can be reused at a later date. File manipulation covers routines that
enable us to determine the status of a file and to perform certain operations to keep them in
order. These functions are included in the header file <io.h>.
The Directory Manipulation routines in Turbo C++ provide the basic tools necessary to
create, modify and remove directories from the C program. The header file <dir.h> includes
the functions for directory manipulation.
int getdisk(void);
getdisk returns the current drive number (0 = A, 1 = B, 2 = C, etc.)
void fnmerge char *path, char *drive, char *dir, char *name, char *ext);
fnmerge make a full path name from components.
int fnsplit(char *path, char *drive, char *dir, char *name, char *ext);
fnsplit take a file's full path name as a string, split the name into its four components, then
store those components.
68
Programming Languages Lab Session 24
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
fnmerge and fnsplit are invertible. If you split a given path with fnsplit, then merge the
resultant components with fnmerge, you end up with the path.
filelength returns the length (in bytes) of the file associated with handle.
The file handle may be determined by using the macro fileno.
EXERCISES
1. Name the header files that contain file and directory manipulation functions.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
2. Write down a program that asks the user for a file name and then displays the length of
that file in bytes.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
69
Programming Languages Lab Session 24
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
3. Write a program to create a directory xxx (where xxx is your first name). Copy the
noname00 file from tc\bin\ to xxx. Now delete this noname00 from xxx and then also
delete the directory xxx.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
70
Programming Languages Lab Session 245
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 24
OBJECTIVE
Command Line Arguments
THEORY
main( ) is a function that can accept arguments just like other functions. It can also return a
value. main( ) receives arguments from the command line. Use of arguments in the command
line is a useful feature.
main( ) always receives two arguments. The first argument ‘argc’ is the number of command
line arguments and the second argument ‘argv’ is an array of pointers to the individual
arguments. Any of the element may be accessed by referring to them as *(argv + 1), *(argv
+2), and so on (or in the array notation, argv[1], argv[2]). The first string, *(argv +0), is the
full path name of the program itself.
The names argc (for Argument Count) and argv (Argument Value) are traditionally used in
these roles, but any other name could be used instead.
To pass arguments to the main function you first need to create the exe file of the program.
Consider, for example, your program named First.cpp, that would print the total number of
arguments passed and their values. To create the exe file for this program, go to the Compile
Menu and click on Make, or directly press F9. To execute this program, go to the command
prompt and write down the following command:
c:\tc\bin> First
This will simply pass one argument to the main. Hence the value of argc will be 1 and *(argv
+ 0) = “c:\tc\bin\First.exe”.
where: argc = 4
*(argv + 0) = c:\tc\bin\First.exe
*(argv + 1) = 5
*(argv + 2) = 2.3
*(argv + 3) = Programming Languages
71
Programming Languages Lab Session 245
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Note that all these arguments are strings. They are not treated as their original data type. To
print these values simply execute a loop argc times and each time print the required contents
using *(argv + i) or arg[i] with the format specifier being %s.
In order to return a value from main, it is required to specify the data type instead of ‘void’
before the function name. Finally, a return statement is to be used. The following program
returns an integer.
int main(void)
{
int num;
printf(“Enter a number”);
scanf(“%d”, &num);
return num;
}
EXERCISES
1. When a program is executed, how many arguments are passed to the main by default?
___________________________________________________________________________
___________________________________________________________________________
2. What is the value of the argument passed to main by the operating system?
___________________________________________________________________________
___________________________________________________________________________
3. Write a small program that uses the alternate main() declaration syntax given above. In the
body of your main function, just print the value of argc. Compile your program and run it
with various numbers of arguments.
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
72
Programming Languages Lab Session 245
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
________________________________________________________________________
_______________________________________________________________________
4. Write down the command to pass the string “C is my favorite programming lanuage” as
argument to the program comline, whose exe file is present in the folder c:\tc\bin.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
73
Programming Languages Lab Session 25
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 25
OBJECTIVE
Variable Length Arguments
THEORY
Usually, when we write a function, we know beforehand the number and type of arguments
that it will take. In certain cases it is not known what would be the arguments to the functions.
Functions like printf, scanf etc can take a variable number of arguments. The parameter-
passing conventions in C help us to access a variable number of arguments. Upon entry to the
function the first argument appears on the stack (a special data structure that is used to hold
the arguments and addresses of functions) just above the return address (meaning it has the
next higher address). Additional arguments have successively higher addresses. If you could
get to the first argument on the stack and you knew the size of all other arguments you could
retrieve the arguments one by one. This is done by the va_start and va_arg macros. While the
macros help us access the arguments on the stack, they cannot tell us when the argument list
ends. This is done by adopting a convention. If each argument were a pointer, for example,
you could mark the end of the argument list with a NULL value.
Suppose, we are writing a function findmax to accept a variable number of integers and
return the largest of the arguments. Since, we want positive numbers only, we assume that a
value of –9999 indicates the end of argument list. Here is one way to implement the findmax
function.
va_list argp;
va_start(argp, firstint);
x = firstint;
74
Programming Languages Lab Session 25
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
if(maxval<x) maxval = x;
x = va_arg(argp, int);
return (maxval);
The variable argp of type va_list is used to point to arguments. The first step in accessing the
arguments is to use va_start to initialize argp. The ANSI standard requires that a function accepting a
variable number of arguments must have at least one argument. The va_start macro uses the address of
this compulsory first argument to set up argp. Once this is done, you can get subsequent arguments by
#include<stdio.h>
#include<stdarg.h> {
va_list arg_ptr;
double d_value;
getch(); while(*string!='\0')
} {
75
Programming Languages Lab Session 25
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
putstring(buffer); ch=va_arg(arg_ptr,char);
//puts putch(ch);
gives
break;
linefeed so
76
Programming Languages Lab Session 25
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
x=wherex();
y++;
case's': //string
if(y>25)
p=va_arg(arg_ptr,char*);
{
putstring(p);
y=25;
break;
putch('\n');
putch('\r');
default:
}
return;
gotoxy(x,y);
} //switch
string++;
ends
string++; } //else
ends
} //if
ends }
//while ends
else if(*string=='\n') //An Escape
Sequence: \n
{ }
//print ends
putch('\n');
putch('\r');
string++;
void putstring(char *ptr)
}
{
else if(*string=='\t') //An Escape
while(*ptr!='\0')
Sequence: \t
{ putch(*ptr++);
77
Programming Languages Lab Session 25
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXERCISES
1. Show output of the following program.
void main(void)
{
clrscr();
char ch='H';
int i=5;
char string[]="Programming Languages";
print("Character:\t%c\nInteger:\t%d\nString:\t%s\n
Percentage:\t%f%%",ch,i,string,83.21);
getch();
}
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
78
Programming Languages Lab Session 25
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
79
Programming Languages Lab Session 25
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
80
Programming Languages Lab Session 27
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 26
OBJECTIVE
Hardware Interfacing through User-developed Programs
THEORY
Hardware interfacing is a very important feature of C language. There are various approaches to
interact with the hardware. These include:
To receive a byte of data from a particular particular the macro inp or the function inportb
may be used. Similarly to receive a word of data from a particular port the macro inpw or the
function inport may be used.
81
Programming Languages Lab Session 27
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
The function used to make a software interrupt occur and thereby invoke a ROM-BIOS
function is a standard library function called int86( ). The ‘int’ stands for ‘interrupt’ and the
‘86’ refers to the 8086 family of microprocessors. The function needs three arguments:
The first union variable represents values being sent to the ROM-BIOS routine, and the
second represents the values being returned from the ROM-BIOS routines to the calling C
program. The values are passed to and returned from ROM-BIOS routines through CPU
registers.
82
Programming Languages Lab Session 27
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
These functions can broaden the range of colors from 16 to 256. Now we use the above
functions in a program as:
void main(void)
{
char r,g,b;
int color= RED;
int *driver = DETECT, *mode;
initgraph(driver, mode, ”c:\\tc\\bgi”);
get_color(color, &r, &g, &b); //get components of
//original color
set_color(color,r+100, g-200,b); //set new color values
setbkcolor(color); //use the C built-in function to
//set the background to your //desired color
getch();
closegraph();
}
EXERCISES
1. Implement the functionality of gotoxy() which is used to place the cursor at the desired
location on the screen by specifying the x and y coordinates. For this first select the active
page, for that generate interrupt with interrupt number 0x10, service number is 5 hex and
Page number (in this case insert 1) in register al. Then use following data to move the
cursor:
Interrupt Number: 0x10 (Interrupt for Video routines)
Input registers: ah (Service number) = 2 Hex.
dh = x- coordinate value
dl = y- coordinate value
Output registers: None
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
83
Programming Languages Lab Session 27
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
2. Write a C program that would send a byte of data to the port address 1f Hex.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
84
Programming Languages Lab Session 27
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 27
OBJECTIVE
Parallel Port Interfacing
THEORY
Parallel port interfacing is a simple and inexpensive tool for building computer controlled devices
and projects. The simplicity and ease of programming makes parallel port popular in electronics
hobbyist world. You can see the parallel port connector in the rear panel of your PC. It is a 25 pin
female (DB25) connector (to which printer is connected). On almost all the PCs only one parallel
port is present, but you can add more by buying and inserting ISA/PCI parallel port cards.In
computers, ports are used mainly for two reasons: Device control and communication. We can
program PC's Parallel ports for both purposes. In PC there is always a D-25 type of female
connector having 25 pins, the function of each pins are listed below.
Parallel ports are easy to program and faster compared to the serial ports. But main disadvantage
is it needs more number of transmission lines. Because of this reason parallel ports are not used in
long distance communications. The Pins having a bar over them means that the signal is inverted
by the parallel port's hardware. If a 1 were to appear on the 11 pin [S7], the PC would see a 0.
Only the Data Port will be covered in this Lab.
Sending commands involves only the data pins [D0 to D7].Though it is possible to use the some
other pins as input, we'll stick to the basics. The word "Parallel" denotes sending an entire set of 8
bits at once [That's why Parallel Port term]. However we can use the individual pins of the port ;
sending either a 1 or a 0 to a peripheral like a motor or LED.
Example:
#include <stdio.h>
#include <conio.h>
#include <dos.h>
void main(void)
{
outportb(0x378,0xFF);
}
Now take an LED and put one terminal at pin2 and the other to pin 18,it would glow.[Use a 2K
resistor in series with the LED, otherwise you'll end up ruining your LED, or source too much
current from the port pin] To switch it off Use this command outportb(0x378,0x00); Instead of the
line outportb(0x378,0xFF);
Explaination of outportb(0x378,0x00) & outportb(0x378,0xFF) cmmands:
0x378 is the parallel port address.For a typical PC, the base address of LPT1 is 0x378 and of PT2
is 0x278. The data register resides at this base address , status register at base address + 1 and the
85
Programming Languages Lab Session 27
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
control register is at base address + 2. So once we have the base address , we can calculate the
address of each registers in this manner. The table below shows the register addresses of LPT1
and LPT2.
EXERCISE
1. Construct an interfacing circuit to control the direction of DC motor using the parallel
port.
86
Programming Languages Lab Session 29
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 28
OBJECTIVE
Mouse Interfacing using Programs in C-Language
THEORY
Mouse is a hardware device, and it may be interfaced in C programs using the ROM-BIOS
routines. Using these routines, the mouse may be initialized and by supplying different values
(service numbers) to the AX register and issuing the interrupt number 33h, different mouse
functions may be accessed. Consider the following code that displays the current x and y
coordinates and also whether a particular mouse button is pressed or not. For this purpose,
first the mouse is initialized, its region of operation is specified and the mouse pointer is
displayed. Then a function is developed to retrieve the mouse coordinates and the button
status:
#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include <graphics.h>
#include <stdlib.h>
87
Programming Languages Lab Session 29
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
exit(0);
}
gotoxy(1,2);
printf("Left Button");
gotoxy(15,2);
printf("Right Button");
getche();
closegraph();
}
void restrictmouseptr(int x1,int y1, int x2, int y2) //restricts mouse movement
{
i.x.ax = 7;
i.x.cx = x1;
i.x.dx = x2;
int86(0x33,&i,&o);
i.x.ax = 8;
i.x.cx = y1;
i.x.dx = y2;
int86(0x33,&i,&o);
}
88
Programming Languages Lab Session 29
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXERCISES
1. Extend the above program to draw a small rectangle (like a popup menu) whenever the
user press the right mouse button.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
89
Programming Languages Lab Session 29
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
90
Programming Languages Lab Session 30
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 29
OBJECTIVE
Type and Storage Classes
THEORY
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the scope and
lifetime of a variable.There are 4 types of storage class:
1. automatic
2. external
3. static
4. register
Local Variable
The variables declared inside the function are automatic or local variables.The local
variables exist only inside the function in which it is declared. When the function
exits, the local variables are destroyed.
int main()
{
int n; // n is a local varible to main() function
... .. ...
}
void func() {
int n1; // n1 is local to func() fucntion
}
Global Variable
Variables that are declared outside of all functions are known as external variables.
External or global variables are accessible to any function.
91
Programming Languages Lab Session 30
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
int main()
{
++n; // variable n is not declared in the main() function
display();
return 0;
}
void display()
{
++n; // variable n is not declared in the display() function
printf("n = %d", n);
}
Output
n=7
Suppose, a global variable is declared in file1. If you try to use that variable in a
different file file2, the compiler will complain. To solve this problem,
keyword extern is used in file2 to indicate that the external variable is declared in
another file.
Register Variable
The register keyword is used to declare register variables. Register variables were
supposed to be faster than local variables. However, modern compilers are very good
at code optimization and there is a rare chance that using register variables will make
your program faster. Unless you are working on embedded system where you know
how to optimize code for the given application, there is no use of register variables.
Static Variable
static int i;
92
Programming Languages Lab Session 30
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
The value of a static variable persists until the end of the program.
int main()
{
display();
display();
}
void display()
{
static int c = 0;
printf("%d ",c);
c += 5;
}
Output
0 5
During the first function call, the value of c is equal to 0. Then, it's value is increased
by 5.During the second function call, variable c is not initialized to 0 again. It's
because c is a static variable. So, 5 is displayed on the screen.
93
Programming Languages Lab Session 30
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 30
OBJECTIVE
Project
THEORY
Select a project based on the following areas
94