0% found this document useful (0 votes)
8 views

Programming Fundamental Lab Manual

The document is a lab manual for Programming Fundamentals at the Khadim Ali Shah Bukhari Institute of Technology, compiled by Mr. Saad Ali Asif. It outlines the objectives, scope, and structure of the manual, which is designed to provide students with practical training in programming using C and C++. The manual includes exercises, theoretical explanations, and guidelines for using the Turbo C IDE.

Uploaded by

muneefkirmani485
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Programming Fundamental Lab Manual

The document is a lab manual for Programming Fundamentals at the Khadim Ali Shah Bukhari Institute of Technology, compiled by Mr. Saad Ali Asif. It outlines the objectives, scope, and structure of the manual, which is designed to provide students with practical training in programming using C and C++. The manual includes exercises, theoretical explanations, and guidelines for using the Turbo C IDE.

Uploaded by

muneefkirmani485
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Khadim Ali Shah Bukhari Institute of Technology

84- -34314970

Lab Manual/CSIS/01

Lab Manual
Programming Fundamentals

Compiled by: Mr. Saad Ali Asif Date: 16-March-2022


Lecturer

1st Review by: Ms. Anum Yaseen Date: 17-March-2023


ISO/QEC Representative

2nd Review by: Dr. Shafiq-ur-Rehman Massan Date: 19-March-2023


Computer Science Representative

Approved by: Prof. Dr. Kashif Mehmood Date: 20-May-2022


Dean
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:

Management
Page Revision Previous Clause Updated Clause
Effective Date Representative
No. No. Details Details
Signature

Khadim Ali Shah Bukhari Institute of Technology ii


Khadim Ali Shah Bukhari Institute of Technology
84- -34314970

Section 1 Circulation

01 Director
02 Chairman of CSIS
03 Head of IT
04 Management Representative
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Section 2 Departmental Objective


Quality Objectives
The IT personnel shall always strive to:

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

The manual is specific for the department


01 The manual shall follow
of CSIS and shall serve as a tool for
the course work
teaching students

The manual shall ensure


02 that the CLO’s and PLO’s
The experiments are verifiable and the
outcomes are measurable and verifiable
are quantified properly

The manual shall ensure The course syllabi of this manual is


03 that the CLO’s and PLO’s attainable and fully conversant with the
are attained latest tools

The experiments are


04 carried out using standard
The experiments are realistic and
observable
equipment

The timeline for the


05 manual shall be attained in
The experiments shall be conducted in a
timely manner
a timely manner

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 4
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Section 3 Scope Of The Manual


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

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 5
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Section 4 IT Compliant Process


The entire process of the manual shall be compliant to the best practices prevailing the in the IT
department, which is the curator and responsible for maintenance of the lab.
Section 5 Software
There are many software being utilized in programming fundamental Lab. The use of software
shall be checked and governed by the IT policy of the institute.
Section 6 Preventive Maintenance for Hardware & Software
The preventive maintenance of hardware and software shall be governed by the IT policy of the
institute.
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)

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 6
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

TABLE OF CONTENTS

SECTION 1 CIRCULATION ........................................................................................................... 3

SECTION 2 DEPARTMENTAL OBJECTIVE ..................................................................................... 4


3.1 Scope............................................................................................................................................................5
3.2 Purpose........................................................................................................................................................5
3.3 Responsibility .............................................................................................................................................5
3.4 The Department .........................................................................................................................................5
3.5 Departmental Chart ...................................................................................................................................5

IDE & PROGRAMMING ENVIRONMENT............................................................................................ 9

C BUILDING BLOCKS ....................................................................................................................... 14

DECISION MAKING THE IF AND IF-ELSE STRUCTURE ...................................................................... 19

SWITCH CASE ................................................................................................................................. 23

DEBUGGING AND SINGLE-STEPPING OF C PROGRAMS .................................................................. 25

LOOPS IN C-LANGUAGE.................................................................................................................. 29

NESTED LOOP .......................................................................................................................... 33

USER DEFINED FUNCTIONS ................................................................................................ 38

ARRAYS IN C-LANGUAGE .................................................................................................... 40

POINTERS .................................................................................................................................. 43

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 7
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

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

provided with the syntax of the statements or commands which will be

used to make the programs of exercises. In order to facilitate the students

some program segments are also provided explaining the use of

commands. For a wide scope of usage of the commands several examples

are also given so that the students can understand how to use the

commands.

The conditions, limitations and memory allocation are also mentioned

where necessary. This book starts the programming of C Language from

the scratch and covers most of the programming structures of C-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++. One lab on Object

Oriented Programming C++ is given in the last which gives the basic idea

of OOP.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 8
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Programming Fundamentals – Lab 01

IDE & Programming Environment


OBJECT

Introduction of Turbo C IDE and Programming Environment

THEORY

The Development Environment - Integrated Development Environment (IDE):


The Turbo C compiler has its own built-in text editor. The files you create with text editor are called
source files, and for C++ they typically are named with the extension .CPP, .CP, or .C.

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.

Invoking the IDE


To invoke the IDE from the windows you need to double click the TC icon in the directory c:\tc\bin.
The alternate approach is that we can make a shortcut of tc.exe on the desktop. 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.

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.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 9
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.

Making an Executable File


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 .c 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.
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).

Compiling the Source Code


Although the source code in your file is somewhat cryptic, and anyone who doesn't know C will
struggle to understand what it is for, it is still in what we call human-readable form. But, for the
computer to understand this source code, it must be converted into machine-readable form. This is
done by using a compiler. Hence, compiling is the process in which source code is translated into
machine understandable language.

It can be done by selecting Compile option from menu bar or using key combination Alt+F9.

Creating an Executable File with the Linker


After your source code is compiled, an object file is produced. This file is often named with the
extension .OBJ. This is still not an executable program, however. To turn this into an executable
program, you must run your linker. C programs are typically created by linking together one or
more OBJ files with one or more libraries. A library is a collection of linkable files that were
supplied with your compiler.

Compiling and linking in the IDE


In the Turbo C IDE, compiling and linking can be performed together in one step. There are two
ways to do this: you can select Make EXE from the compile menu, or you can press the [F9] key.

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.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 10
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

The Development Cycle


If every program worked the first time you tried it that would be the complete development cycle:
Write the program, compile the source code, link the program, and run it. Unfortunately, almost
every program, no matter how trivial, can and will have errors, or bugs, in the program. Some bugs
will cause the compile to fail, some will cause the link to fail, and some will only show up when
you run the program.

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.

Exiting the 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 [Alt][X] Combination. Exit from the File Menu or press

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 11
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>

3. Make the following changes to the program. What Errors are observed?
i. Write Void instead of void .

ii. Write void main (void);

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 12
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

iii. Remove the semi colon ‘;’.

iv. Erase any one of brace ‘{’ or ‘}’.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 13
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Programming Fundamentals – Lab 02

C BUILDING BLOCKS

OBJECT

C Building Blocks

THEORY

In any language there are certain building blocks:


• Constants
• Variables
• Operators
• Methods to get input from user(scanf( ), getch( ) etc.)
• Methods to display output (Format Specifier, Escape Sequences etc.) etc.

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.

Variables and Constants


If the value of an item is to be changed in the program then it is a variable. If it will not change
then that item is a constant. The various variable types (also called data type) in C are: int, float,
char, long ,double etc they are also of the type signed or unsigned.

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


\t => tab
\b => back space
\r => carriage return
\” => double quotations
\\ => back slash, etc.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 14
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Taking Input from the User


The input from the user can be taken by the following techniques: scanf( ), getch( ), getche( ),
getchar( ) etc.

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: && , || , !

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 15
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

2. Write down C statements to perform the following operations:


i. z = 4.2(x+y)5/z – 0.52x/(y+z) (x+y) 2

ii. x = a2 +2ab+b 2

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 16
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

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);

4. What will be the output if a=5, printf(“%d”,++a); printf(“%d”,a++);

5. Point out the Errors, if any, in the following C statements:


(a). 3.14 * r * r * h = vol_of_cyl ;

(b). volume = 3.14 * r ^ 2 * h

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 17
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

6. Write a C program to find sum and average of three numbers.

7. Print following shape using simple printf statements

*****
****
***
**
*

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 18
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Programming Fundamentals – Lab 03

DECISION MAKING THE IF AND IF-ELSE STRUCTURE

OBJECT

Decision making the if and if-else structure

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.

The simplest form of an if (expression)


statement;
if statement is:

The if-else statement


Often your program will want to take one branch if your condition is true, another if it is false. If
only one statement is to be followed by the if or else condition then there is no need of
parenthesis. The keyword if (expression) { statements;
}
else can be used to perform this functionality:

else

{ statement/s; }

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 19
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

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

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 20
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

2. Write a program that inputs an integer – determine if it is even or odd.

3. Write a program which takes a character input and checks whether it is vowel or
consonant

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 21
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

4. Write a program which takes 3 integers as input and prints the largest one.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 22
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Programming Fundamentals – Lab 04

SWITCH CASE

OBJECT

Decision making the Switch case and conditional operator.

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 switch Statement


Unlike if , which evaluates one value, switch statements allow you to branch on any of a number
of different values. There must be break at the end of the statements of each case otherwise all the
preceding cases will be executed including the default condition. The general form of the switch
statement is:
switch (identifier variable)
{
case identifier One: statement;

case identifier Two: statement;

....
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.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 23
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

The conditional operator takes three expressions and returns a value: (expression1) ?
(expression2) : (expression3)

It replaces the following statements of if else structure


If(a>b) c=a; else c=b;
can be replaced by c=(a>b)?:a:b
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)

6. Write a program to make a simple calculator which should be able to do + , - , *


, / operations

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 24
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Programming Fundamentals – Lab 05

DEBUGGING AND SINGLE-STEPPING OF C PROGRAMS

OBJECT

Debugging and Single-Stepping of C 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.

One Step at a Time


The first thing that the debugger can do for you is slow down the operation of the program. One
trouble with finding errors is that a typical program executes in a few milliseconds, so all you can
see is its final state. By invoking C++’s single-stepping capability, you can execute just one line
of the program at a time. This way you can follow where the program is going.

Consider the following program:


void main(void)
{
int number, answer=-1; number = -50; if(number < 100)
if(number > 0)
answer = 1;
else
answer = 0;
printf(“answer is %d\n”, answer);
}

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

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 25
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

-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

if (num < 100 )

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.

Resetting the Debugger


Suppose you’ve single stepped part way through a program, and want to start over at the beginning.
How do you place the run bar at the top of the listing? You can reset the debugging process and
initialize the run bar by selecting the Program Reset option from the Run menu.

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

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 26
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

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.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 27
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

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

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 28
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Programming Fundamentals – Lab 06

LOOPS IN C-LANGUAGE
OBJECT

Looping constructs in C-Language

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

Nesting may extend these loops.

The for Loop for(initialize(optional);condition(compulsory);increment(optional)


{
Body of the Loop;
}
This loop runs as long as the condition in the center is true. Note that there is no semicolon
after the “for” statement. If there is only one statement in the “for” loop then the braces may be
removed. If we put a semicolon after the for loop instruction then that loop will not work for any
statements.

The while Loop


while(condition is true)
{
Body of the Loop;}
This loop runs as long as the condition in the parenthesis is true. Note that there is no semicolon

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 29
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

after the “while” statement. If there is only one statement in the “while” loop then the braces may
be re moved.

The do-while Loop


do
{
Body of the Loop;
}
while(condition is true);

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

1. Write down the output of the following program statements


i. for (i=1; i<= 10;i++)
printf(“%d \n”,i);

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 30
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

ii. int a = 10, b = 10;


for(inti=1;i<=a;i++)
{
a++;
b--;
printf(“a = %d,b=%d\t”,a,b);
}

2. Write a program to generate a series of first 50 even numbers

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 31
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

3. Write a program to generate tables from 2 with first 10 terms

4. Write a program to print all the ASCII code.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 32
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Programming Fundamentals – Lab 07

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

The Nested for Loop


for(initialize;condition;increment)
{
for(initialize;condition;increment)
{
Body of the loop;
}
}
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.

The nested while Loop


while(condition is true)
{
while(condition is true)
{

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 33
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Body of the loop;


}
Body of the loop;
}
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.

The Nested do-while Loop


do
{
do
{
body of the loop;
}
while(condition is true);

body of the loop;


}
while(condition is true);

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.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 34
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

EXERCISE

1. Write down the output of the following program statements

for (int a=1;j=1; j<=5;j++)


for (i=1; i<=5;i++)
{
printf(“%d\n”,a);
a++;
}

2. Write a program which Prints the following pattern up to 10 lines

1
22
333
4444
55555

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 35
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

3. Write a program which Prints the following pattern up to 10 lines


1
12
123
1234
12345

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 36
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

4. Write a program to produce the following output:


ABCDEFG FEDCBA
ABCDEFFEDCBA
ABCDE EDCBA
ABCDDCBA
ABC CBA
AB BA
AA

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 37
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Programming Fundamentals – Lab 08

USER DEFINED FUNCTIONS


OBJECT

Functions in C-Language programming

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.

i. Declaring a function or prototype:


The general structure of a function declaration is as follows:
return_type function_name(arguments);

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.

ii. Calling a function:


The function call is made as follows:
return_type = function_name(arguments);

ii. Defining a function:


All the statements or the operations to be performed by a function are given in the function
definition which is normally given at the end of the program outside the main.
Function is defined as follows
return_type function_name(arguments)
{ Statements;
}

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.

• Functions that do not take arguments but return something.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 38
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

• Functions that take arguments and return something.

A function that returns nothing must have the return type “void”. If nothing is specified then the
return type is considered as “int”.

EXERCISE

1. Write a program to find a. Surface area (A=4pr 2 ) b. volume(v=4/3 p 3 )


of a sphere using functions make a function for finding powers of radius.

2. Write a user defined function which takes input and calculate its factorial

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 39
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Programming Fundamentals – Lab 09

ARRAYS IN C-LANGUAGE
OBJECT

Arrays in C (one dimensional and Multidimensional)

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.

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 40
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

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

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 41
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

3. What would be the output of the following Program:

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

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 42
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

Programming Fundamentals – Lab 10

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:

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 43
KHADIM ALI SHAH BUKHARI INSTITUTE OF TECHNOLOGY

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 ) ;
}

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 44
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;
}

PROGRAMMING FUNDAMENTALS CS-XXX


Page | 45

You might also like