Programming Fundamental Lab Manual
Programming Fundamental Lab Manual
84- -34314970
Lab Manual/CSIS/01
Lab Manual
Programming Fundamentals
REVISION HISTORY
This Lab Manual is reviewed to ensure its continuing relevance to the Computer Science & Information Systems
Department of KASBIT institute. A record of contextual additions or omissions is given below:
Management
Page Revision Previous Clause Updated Clause
Effective Date Representative
No. No. Details Details
Signature
Section 1 Circulation
01 Director
02 Chairman of CSIS
03 Head of IT
04 Management Representative
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
1) Follow the CLO’s and PLO’s as outlined in the subject course information sheet
2) The medium of instruction is English
3) The practical’s are intended to give a thorough insight into Programming Fundamentals
SMART Objectives:
Accomplishment
S. No Objectives Plan/Strategy
Date
TABLE OF CONTENTS
LOOPS IN C-LANGUAGE.................................................................................................................. 29
POINTERS .................................................................................................................................. 43
This work book is specially designed to help the students to generate their
own logic for the accomplishment of the assigned tasks. Every lab is
are also given so that the students can understand how to use the
commands.
For some commands or structures more than one lab are designed so that
the students can thoroughly understand their use. This lab book leads the
Oriented Programming C++ is given in the last which gives the basic idea
of OOP.
THEORY
The C Developing Environment, also called as Programmer’s Platform, is a screen display with
windows and pull-down menus. The program listing, error messages and other information are
displayed in separate windows. The menus may be used to invoke all the operations necessary to
develop the program, including editing, compiling, linking, and debugging and program execution.
Default Directory
The default directory of Turbo C compiler is c:\tc\bin.
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.
Opening a New Window
To type a program, you need to open an Edit Window. For this, open file menu and click “new”. A
window will appear on the screen where the program may be typed.
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.
It can be done by selecting Compile option from menu bar or using key combination Alt+F9.
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.
Whatever type of bug you find, you must fix it, and that involves editing your source code,
recompiling and relinking, and then rerunning the program.
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.
EXERCISE
1. Type the following program in C Editor and execute it. Mention the Error.
void main(void)
{
printf(“This is my first program in C ”);
}
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. What Errors are observed?
i. Write Void instead of void .
C BUILDING BLOCKS
OBJECT
C Building Blocks
THEORY
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 => float 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:
Operators
There are various types of operators that may be placed in three categories:
Arithmetic Operators: + - * / %
Assignment: = += -= *= /= %=
(++, -- may also be considered as assignment operators)
Relational: < > <= >= == !=
Logical: && , || , !
EXERCISE
1. Write a program which shows the function of each escape sequence character. eg printf(“alert
ring bell rings like \a\a\a\a\a\a\a\a\a\a\a\a\a\a”);
printf(“the tab is inserted like \t this”);etc
ii. x = a2 +2ab+b 2
3. What will be the out put of the mix mode use of integers and float. a=5/9, b=5.0/9;
printf(“%f,%f”,a,b);
*****
****
***
**
*
OBJECT
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. The ‘if’ statement, the if-else statement, and the switch statement. Another less
commonly used structure is the conditional operator.
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 or the conditions with relational and
logical operators are also included.
else
{ statement/s; }
EXERCISE
1. Write a program which takes three sides a, b and c of a triangle input and calculates its
area if these conditions are satisfied a+b>c, b+c>a, a+c>b
(Help a= s(s-a)(s-b)(s-c), where s=(a+b+c)/2
3. Write a program which takes a character input and checks whether it is vowel or
consonant
4. Write a program which takes 3 integers as input and prints the largest one.
SWITCH CASE
OBJECT
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. The ‘if’ statement, the if-else statement, and the switch
statement. Another less commonly used structure is the conditional operator.
....
case identifier N: statement;
default: statement;
}
Conditional Operator
The conditional operator ( ?: ) is C’s only ternary operator; that is, it is the only operator to
take three terms.
The conditional operator takes three expressions and returns a value: (expression1) ?
(expression2) : (expression3)
EXERCISE
1. Write a program which takes a character input and checks whether it is vowel or
consonant. (Using switch case)
OBJECT
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
–1.
Number, we find that answer is set to 0 at the end of the program, instead of staying
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
ifstatement:
This statement is true (since number is –50); so, as we would expect the run bar moves to
the second if statement:
if(num>0)
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 need to put braces around the second
if statement is false, which leads to erroneous results. We
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.
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.
EXERCISE
1. Type in the following program and find out the error using the Turbo C Debugger.
#include<stdio.h>
void main(void)
{
int a=4,b=5,i;
printf(“ enter the number “):
scanf(“%c”,b);
if(a=40)
{ a++; b--;
} printf(“%d”,i); printf(“%d”,a); printf(“%d”,b);
}
Mention the error. Correct this program by locating the error through the debugger and
rewrite the correct program statements
LOOPS IN C-LANGUAGE
OBJECT
THEORY
Types of Loops
There are three types of Loops:
1) for Loop
simple for loop
nested for loop
2) while Loop
1. simple while loop
2. nested while loop
3) do - while Loop
simple do while loop
nested do while loop
after the “while” statement. If there is only one statement in the “while” loop then the braces may
be re moved.
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 executed if the
condition is not satisfied.
EXERCISE
Nested Loop
OBJECT
Nested looping
THEORY
Types of Loops
There are three types of Loops:
There are three types of Loops:
1) for Loop
a. simple for loop
b. nested for loop
2) while Loop
a. simple while loop
b. nested while loop
3) do - while Loop
a. simple do while loop
b. nested do while loop
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. The inner loop runs as many times as there is the limit of the condition
of the external loop. This loop runs as long as the condition in the parenthesis is true. We can nest
many loops inside as there is the requirement.
EXERCISE
1
22
333
4444
55555
THEORY
Functions are used normally in those programs where some specific work is required to be done
repeatedly and looping fails to do the same. Three things are necessary while using a function.
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 me ntioned for arguments in the function declaration.
There are certain functions that you have already used e.g:getche( ), clrscr( ), printf( ), scanf( )
etc.
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.
A function that returns nothing must have the return type “void”. If nothing is specified then the
return type is considered as “int”.
EXERCISE
2. Write a user defined function which takes input and calculate its factorial
ARRAYS IN C-LANGUAGE
OBJECT
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 Long Array. 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
A Multidimensional 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,
int a[5][10]
declares an array of 50 integers, named a. Its declaration shows that array a comprises of 5 one
dimensional arrays and each one dimensional array contains 10 elements.
When the compiler sees this declaration, it sets aside enough memory to hold all 50 elements.
Because each integer requires 2 bytes, this declaration sets aside 100 contiguous bytes of memory.
EXERCISE
1. Write a program that takes 10 integers as input and prints the largest integer and its
location in the array.
2. Write a program which takes a string as input and counts total number of vowels in that
main( )
{
int a[5] ;
int i ;
for ( i = 0 ; i <= 4 ; i++ )
printf ( "\n%d", a[i] ) ;
}
4. Write a program that adds up two 4x4 arrays and stores the sum in third array
POINTERS
OBJECT
Pointers with arrays and function.
THEORY
A pointer is the most effective tool to pass an array to a function. If pointers are involved than a
function can return more than one values at a time.
We have to pass only the address and size of the array to the function and we can make as many
changes in the function as we want. For example if we want to add 5 in each array element using
functions. Then similarly string arrays and multidimensional arrays can also be passed to functions
by their addresses and size
void add(int *,int);
void main(void)
{int s[10],i;
printf(“enter ten integers”);
for(i=0,i<10,i++)
{printf(“\n enter integer no %d :”,i+1);
scanf(“%d”,&s[i]);
} add(s,10); for(i=0,i<10,i++)
{printf(“\n integer no %d :%d”,i+1,s[i]);
}
}
void add(int *p,int x)
{int j;
for (j=0;j<x;j++)
{
*p=*p+5;
p++;
}
}
EXERCISE:
main( )
{
int i = 35, *z ;
z = function ( &i ) ;
printf ( "\n%d", z ) ;
}
function ( int *m )
{
return ( m + 2 ) ;
}
2. Point out the errors, if any, in the following Program and prints its output
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}