Programming Fundamental Lab Manual Exercise Solved
Programming Fundamental Lab Manual Exercise Solved
2nd
Khadim Ali Shah Bukhari Institute of Technology
84- -34314970
Lab Manual/CSIS/01
Lab Manual
Programming Fundamentals
Lab Manual/CSIS/01
Revision No.: 00
Execution Date:
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:
Page Revision Effective Previous Clause Updated Clause Management
No. No. Date Details Details Representative
Signature
Section 1 Circulation
0 Director
1
0 Chairman of CSIS
2
0 Head of IT
3
0 Management Representative
4
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
SMART Objectives:
S. Objectives Plan/Strategy Accomplishment
No Date
01
The manual is specific for the department
The manual shall follow
of CSIS and shall serve as a tool for
the course work
teaching students
02
The manual shall ensure
The experiments are verifiable and the
that the CLO’s and PLO’s
outcomes are measurable and verifiable
are quantified properly
03
The manual shall ensure The course syllabi of this manual is
that the CLO’s and PLO’s attainable and fully conversant with the
are attained latest tools
04
The experiments are
The experiments are realistic and
carried out using standard
observable
equipment
05
The timeline for the
The experiments shall be conducted in a
manual shall be attained in
timely manner
a timely manner
Page | 6
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
3.1 Scope
The scope of the manual is limited to the subject of programming fundamentals that is proscribed
for the first semester of Bachelor of Science in Computer Science at the Khadim Ali Shah
Bukhari Institute of Technology.
3.2 Purpose
The purpose of the manual is to provide training about the different aspects of the software
development world to the students.
3.3 Responsibility
The responsibility of change management and draft approval lies with the department of
Computer Science through its representatives and the Chairman.
3.4 The Department
The department of Computer Science and Information Systems is the sole curator of this manual
and shall undertake all measures to keep the contents concurrent and relevant to the subject of
programming fundamentals being taught.
3.5 Departmental Chart
Page | 7
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
Section 7 Related Records
This manual is intended to be utilized with the subject of programming fundamentals at
university level for Bachelor of Computer Science program.
Document No Lab Manual (programming fundamentals) (CSIS/02)
Page | 8
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
TABLE OF CONTENTS
LOOPS IN C-LANGUAGE..................................................................................................................
29
Page | 9
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
POINTERS ..................................................................................................................................
43
their own logic for the accomplishment of the assigned tasks. Every lab
examples are also given so that the students can understand how to use
the commands.
Language. 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 students to the Object Oriented Programming C++.
Page | 10
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
One lab on Object Oriented Programming C++ is given in the last which
OBJECT
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.
Page | 11
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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.
Page | 12
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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.
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.
All the above steps can be done by using Run option from the menu bar or using key
combination Ctrl+F9 (By this linking & compiling is done in one step).
It can be done by selecting Compile option from menu bar or using key combination Alt+F9.
Page | 13
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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.
Page | 14
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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>
Page | 15
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
3. Make the following changes to the program. What Errors are observed?
i. Write Void instead of void .
Page | 16
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
Page | 17
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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.
Page | 18
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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:
&& , || , !
Page | 19
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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
Page | 20
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
ii. x = a2 +2ab+b2
x = (a * a) + (2 * a * b) + (b * b);
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);
a = 5 / 9;
b = 5.0 / 9;
printf("%f,%f", a, b);
Page | 21
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
a = 5;
printf("%d", ++a); // First printf
printf("%d", a++); // Second printf
5. Point out the Errors, if any, in the following C statements: (a). 3.14 * r * r * h = vol_of_cyl ;
vol_of_cyl = 3.14 * r * r * h;
#include <math.h>
volume = 3.14 * pow(r, 2) * h;
Page | 22
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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.
Page | 23
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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
Page | 24
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
3. Write a program which takes a character input and checks whether it is vowel or
consonant
Page | 25
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
4. Write a program which takes 3 integers as input and prints the largest one.
Page | 26
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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;
Page | 27
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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)
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.
EXERCISE
1. Write a program which takes a character input and checks whether it is vowel or
consonant. (Using switch case)
Page | 28
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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
Page | 29
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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.
Page | 30
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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.
Page | 31
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
#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
Page | 32
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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
Page | 33
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
{
Body of the Loop;}
This loop runs as long as the condition in the parenthesis is true. Note that there is no semicolon
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
Page | 34
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
Page | 35
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
Page | 36
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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
Page | 37
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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
Page | 38
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
{
printf(“%d\n”,a); a+
+;
}
1
22
333
4444
55555
Page | 39
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
Page | 40
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
Page | 41
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
OBJECT
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.
Page | 42
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
There are four types of functions depending on the return type and arguments:
• Functions that take nothing as argument and 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
Page | 43
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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.
Page | 44
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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] ) ;
}
Page | 45
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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]);
}
}
Page | 46
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
EXERCISE:
1. Point out the errors, if any, in the following Program:
main( )
{ int i = 35, *z ;
z = function
( &i ) ;
printf ( "\n%d", z ) ;
}
function ( int *m )
{
return ( m + 2 ) ;
}
Page | 47
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY
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;
}
Page | 48