Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
355 views

Computer Programming Lab Manual

computer programming manual will easily guide you that how programming is done with just simple steps

Uploaded by

Muhammad Attique
Copyright
© © All Rights Reserved
0% found this document useful (0 votes)
355 views

Computer Programming Lab Manual

computer programming manual will easily guide you that how programming is done with just simple steps

Uploaded by

Muhammad Attique
Copyright
© © All Rights Reserved
You are on page 1/ 159

CSEE1121: Computer Programming Lab

Name: ___________________________________
Reg No: ___________________________________

Department of Electrical Engineering


Capital University of Science and Technology
Islamabad, Pakistan
© Copy Rights, Department of Electrical Engineering, CUST Islamabad

All Rights Reserved

Prepared by: Muhammad Ali Nagra

pg. ii
S.N0 List of Experiments

1 Introduction to C Programming, Datatypes, Operators


and Statements
2 Selection Control Structures (If-Else, Nested If-Else
and Switch Statements)
3 Repetition Control Structures (For, While and Do-
While loops)
4 Introduction to User Defined Functions

5 Function Parameters and Recursive Functions

6 One Dimensional Arrays

7 Multi-Dimensional Arrays

8 Strings in C Language

9 Pointers in C Language

10 Structures in C Language

11 Nested Structures and Union

12 File Handling in C Language

pg. iii
Lab Safety Rules

 Be sure that all equipment is properly working before using them for laboratory exercises. Any
defective equipment must be reported immediately to the Lab Engineer or Lab Technical Staff.
 Students should keep a safe distance from the circuit breakers, electric circuits or any moving
parts during the experiment.
 Avoid any part of your body to be connected to the energized circuit and ground.
 Switch off the equipment and disconnect the power supplies from the circuit before leaving the
laboratory.
 Make sure that the last connection to be made in your circuit is the power supply and first thing
to be disconnected is also the power supply.
 Equipment should not be removed, transferred to any location without permission from the
laboratory staff.

pg. iv
CSEE1121: Computer Programming Lab

Lab#01

Introduction to C Programming, Datatypes, Operators and


Statements

Objectives:
To familiarize the students with:

 Understanding of c language and development environment


 Compiler, assembler, linker and interpreter
 Steps involved in the program execution
 Algorithm and pseudo codes writing
 Datatypes in C language variable declaration
 Input, output statements and format specifiers
  Different types of operators in c language and their precedence

Normally the C program building process involves four stages and utilizes different „tools‟ such as a
preprocessor, compiler, assembler, and linker.

Compiler
This software, converts the code written in high-level language into object file. Compiler converts all the
files of a given project at once.

Assembler:
While compiler processes high level languages, assembler has the capability of processing only the low
level assembly language. This assembly language is extremely core (microprocessor/platform) specific.

1. Algorithms
An algorithm is procedure consisting of a finite set of unambiguous rules (instructions) which specify a
finite sequence of operations that provides the solution to a problem, or to a specific class of problems
for any allowable set of input quantities (if there are inputs). In other word, an algorithm is a step-by-
step procedure to solve a given problem

Department of Electrical Engineering pg. 1


The term algorithm originally referred to any computation performed via a set of rules applied to
numbers written

Figure 1. Program compilation cycle

in decimal form. The word is derived from the phonetic pronunciation of the last name of Abu Ja'far
Mohammed ibn Musa al-Khowarizmi, who was an Arabic mathematician who invented a set of rules for
performing the four basic arithmetic operations (addition, subtraction, multiplication and division) on
decimal numbers.

An algorithm is a representation of a solution to a problem. If a problem can be defined as a difference


between a desired situation and the current situation in which one is, then a problem solution is a
procedure, or method, for transforming the current situation to the desired one. We solve many such
trivial problems every day without even thinking about it, for example making breakfast, travelling to
the workplace etc. But the solution to such problems requires little intellectual effort and is relatively
unimportant. However, the solution of a more interesting problem of more importance usually involves
stating the problem in an understandable form and communicating the solution to others. In the case
where a computer is part of the means of solving the problem, a procedure, explicitly stating the steps
leading to the solution, must be transmitted to the computer. This concept of problem solution and
communication makes the study of algorithms important to computer science.

Department of Electrical Engineering pg. 2


Throughout history, man has thought of ever more elegant ways of reducing the amount of labor
needed to do things. A computer has immense potential for saving time/energy, as most
(computational) tasks that are repetitive or can be generalized can be done by a computer. For a
computer to perform a desired task, a method for carrying out some sequence of events, resulting in
accomplishing the task, must somehow be described to the computer. The algorithm can be described
on many levels because the algorithm is just the procedure of steps to take and get the result.

2. FLOWCHARTS
Flowcharting is a tool developed in the computer industry, for showing the steps involved in a process. A
flowchart is a diagram made up of boxes, diamonds and other shapes, connected by arrows - each shape
represents a step in the process, and the arrows show the order in which they occur. Flowcharting
combines symbols and flow lines, to show figuratively the operation of an algorithm.

In computing, there are dozens of different symbols used in flowcharting (there are even national and
international flowcharting symbol standards). In business process analysis, a couple of symbols are
sufficient. A box with text inside indicates a step in the process, while a diamond with text represents a
decision point. See the figure for an example.

If the flowchart is too messy to draw, try starting again, but leaving out all of the decision points and
concentrating on the simplest possible course. Then the session can go back and add the decision points
later. It may also be useful to start by drawing a high-level flowchart for the whole organization, with
each box being a complete process that has to be filled out later.

From this common understanding can come a number of things - process improvement ideas will often
arise spontaneously during a flowcharting session. And after the session, the facilitator can also draw up
a written procedure - a flowcharting session is a good way of documenting a process.

Process improvement starts with an understanding of the process, and flowcharting is the first step
towards process understanding.

Flowcharting Symbols
There are 6 basic symbols commonly used in flowcharting of assembly language programs: Terminal,
Process, input/output, Decision, Connector and Predefined Process. This is not a complete list of all the
possible flow chart symbols; it is the ones used most often in the structure of Assembly language
programming.

Department of Electrical Engineering pg. 3


Figure 2: Flowchart Symbols

General Rules for flowcharting


1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit
point for all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally, a flowchart will flow from top to bottom. However, an upward flow can be shown as long as
it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
 From one page to another page.
 From the bottom of the page to the top of the same page.
 An upward flow of more than 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or subroutines)
symbol.
8. All flowcharts end with a terminal or a contentious loop.

Examples of Algorithms and Flowcharts

Example 1. Design an algorithm and the corresponding flowchart for adding the test scores as
givenbelow:

26, 49, 98, 87, 62, 75

Department of Electrical Engineering pg. 4


Figure 3: Sum of number 1

PSEUDOCODE

Pseudocode is an artificial and informal language that helps you develop algorithms. The pseudocode
we present here is particularly useful for developing algorithms that will be converted to structured C
programs. Pseudocode is similar to everyday English; it’s convenient and user friendly although it’s not
an actual computer programming language. Pseudocode programs are not executed on computers.
Rather, they merely help you “think out” a program before attempting to write it in a programming
language like C. Pseudocode consists purely of characters, so you may conveniently type pseudocode
programs into a computer using an editor program. A carefully prepared pseudocode program may be
easily converted to a corresponding C program. This is done in many cases simply by replacing
pseudocode statements with their C equivalents. Pseudocode consists only of action statements—those
that are executed when the program has been converted from pseudocode to C and is run in C.
Definitions are not executable statements—they’re simply messages to the compiler. For example, the
definition tells the compiler the type of variable i and instructs the compiler to reserve space in memory
for the variable. But this definition does not cause any action—such as input, output, a calculation or a
comparison—to occur when the program is executed. Some programmers choose to list each variable
and briefly mention the purpose of each at the beginning of a pseudocode program.

Department of Electrical Engineering pg. 5


Department of Electrical Engineering pg. 6
Control Structures

There are three type of control structures available in C language as shown in the figure below.
1- Sequential
2- Selection
3- Repetition

Figure 4. Sequential, Selection and Repetition Control Structures

1. Setting up Integrated Development Environment (IDE):


Go to start menu-->All Programs-->Micro Soft Visual Studio 2010 and then click on Micro Soft
Visual Studio 2010.

Perform the following steps to setup the IDE for C programming.

 Create a new project by clicking File->New->Project.


 From Installed Template choose other language
 Choose language Visual C++
 In Visual C++ choose tab Win32
 Choose project type Win32 Console Application and then click OK

Department of Electrical Engineering pg. 7


See
the image below,
Figure 5: Selecting a console window program

From the dialog box click on Next button

Figure 6: Program Setup Wizard 1

Next screen is of Application Setting. You need to make sure


Department of Electrical Engineering pg. 8
 Application type is set a Console Application

 In Additional options uncheck the Precompiled Header.

Figure 7: Program Setup 2

After clicking Finish you will find a project has been created with below structure. Open solution
explorer to see the structure

To start programming, right click on Source Files and add a new item. You need to make sure below two
points,
 Select C++ File to add

 But in name change extension to .C, default is .CPP. To work with C language program source file
name should be with extension “.C”. In this case I am giving source file name as Sample1.C

Department of Electrical Engineering pg. 9


Figure 8: Selecting a CPP file and naming in

Now open Sample1.c

2. C - Program Structure

A C program basically has the following form:

 Preprocessor Commands
 Functions
 Variables
 Statements & Expressions
 Comments

The following program is written in the C programming language.


#include <stdio.h>

intmain()
{
/* My first program */
inti=9;
int j=3;

k=i+j;
printf(“The result is %d”, k);
2.1. Preprocessor Commands:
Thesereturn
commands0;tell the compiler to do preprocessing before doing actual compilation. Like #include
}
Department of Electrical Engineering pg. 10
<stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to
actual compilation.

2.2. Functions:
Functions are main building blocks of any C Program. Every C Program will have one or more functions
and there is one mandatory function which is called main() function. This function is prefixed with
keyword int which means this function returns an integer value when it exits. This integer value is
returned using return statement.

2.3. Variables:
Variables are used to hold numbers, strings and complex data for manipulation. You will learn in detail
about variables in next topics

2.4. Statements &Expressions :


Expressions combine variables and constants to create new values. Statements are expressions,
assignments, function calls, or control flow statements which make up C programs.

2.5. Comments:
Comments are used to give additional useful information inside a C Program. All the comments will be
put inside /*...*/ as given in the example above. A comment can span through multiple lines.

3. Data types in C language


In C, variable (data) should be declared before it can be used in program. Data types are the keywords,
which are used for assigning a type to a variable.

Department of Electrical Engineering pg. 11


Table 1: Datatypes in C

Variables:
A variable is just a named area of storage that can hold a single value (numeric or character). The C
language demands that you declare the name of each variable that you are going to use and its type.

The Programming language C has two main variable types

 Local Variables
 Global Variables

We will discuss about local and global variableslater.

4. Syntax for declaration of a variable

data_typevariable_name;

For example, if you want to declare a variable of type integer then the syntax will be

int number;

Department of Electrical Engineering pg. 12


5. Input:
In any programming language input means to feed some data into program. This can be given in the
form of file or from command line. C programming language provides a set of built-in functions to read
given input and feed it to the program as per requirement. The most basic command for user input is
“scanf”, Lets say you want to take an integer as input from the user:
scanf(“%d”,&i);
The variable ‘i’ now has whatever integer the user has entered on the console. Now, Lets say you want
to take a floating point input:
scanf(“%f”,&i);

Similarly, this can be done with other datatypes like double, character etc.

6. Output:
In any programming language output means to display some data on screen, printer or in any file. C
programming language provides a set of built-in functions to output required data.
Here we will discuss only one input function and one output function just to understand the meaning of
input and output.
Let’s suppose you want to display your name on the console window, what you’ll do is:
printf(“My name is XYZ”);
And than you want to display your marks in which are stored in a variable ‘k’:
printf(“My marks are %d, k”);

7. 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:
\n => new line
\t => tab
\b => back space
\r => carriage return
\” => double quotations
\\ => back slash etc.

Department of Electrical Engineering pg. 13


Table 2: Operators according to their precedence in C language

Department of Electrical Engineering pg. 14


Lab activities:

Activity 1: Compile the C program below and remove the errors.

#include stdio.h
void main
scanf(“%d”,i);
intI,j
k=i+j;
print(“%d,k);

Activity 2: Write a C program to print the following lineson console

*****************
* Your name *
* Your Roll No *
*****************

Activity 3: Write a C program which takes two floating points and one character from the user, add
the numbers, divide the sum by 5 and display the output on the console

Activity 4: Write a C program to compute the area and circumference of a circle, take the radius as
input from user, calculate the radius and the area, Display the resulting values on the console. The
program should define the value of pi (π) as constant.
A=πr2
C=2πr

Department of Electrical Engineering pg. 15


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 16


Department of Electrical Engineering pg. 17
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
(10) limited competence competence competence
competence

Marks Obtained

Department of Electrical Engineering pg. 18


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering pg. 19


CSEE1121: Computer Programming Lab

Lab#02

Selection Control Structures (If-Else, Nested If-Else and


Switch Statements)
Objective:

Objectives of this lab are:

 Understanding of control structures in C Language


 Overview of theif-else and nested if–else control structures
 Overview of the Switch Statement
 Interpret flow-charts and convert them into C Programs

Conditional statements in C Language


Conditional statements control the sequence of statements, depending on the condition

We will look into following conditional statements.

 If
 If-Else
 Nested If-Else
 Switch Statement

Department of Electrical Engineering pg. 20


1. If conditional statement in C Language
If the condition is true the statements inside the parenthesis { }, will be executed, else the control will be
transferred to the next statement after if.

Syntax: #include<stdio.h>
//this program demonstrate the simple if
if(condition) statement
{ voidmain()
Statement1; {
..... int number1;
Statement n; int number2;
}

printf("Enter NUmber1 :");


Flow chart
scanf("%d %d",&number1,&number2);

if(number1>number2)
{
printf("\n a is greater than b");
}

Figure 1: If Condition
2. if else in C Language
In if else if the condition is true the statements between if and else is executed. If it is false, the “else
“statement will be executed.
#include<stdio.h>
//this program demonstrate the simple if
Syntax for if else: statement
voidmain()
if(condition) {
{ int number1;
Statement1; int number2;
.....
Statement n;
} printf("Enter NUmber1 :");
else
{ scanf("%d %d",&number1,&number2);
Statement1;
..... if( number1 > number2 )
Statement n; {
} printf("\n number 1 is greater than
number 2");
}
else
{
printf("\n number 2 is greater than
number 1");
}
Department of Electrical Engineering } pg. 21
Flow chart
Figure 2: If-Else condition

3. Nested if- else inC Language


In else if, if the condition is true the statements between if and else if is executed. If it is false the
condition in else if is checked and if it is true it will be executed. If none of the condition is true the
statement under else is executed.

Syntax for else if : voidmain()


{
int number1;
if(condition) int number2;
{ printf("Enter NUmber1 :");
Statements; scanf("%d %d",&number1,&number2);
} if( number1 > number2 )
else if (condition) {
{ printf("\n number 1 is greater");
Statements; }
} else if(number1 < number2 )
else {
{ printf("\n number 2 is greater");
Statements; }
} else
{
printf("\n both are equal");
}
}

4. Switch statement in C Language


Switch statements can also be called matching case statements. If matches the value in variable
(switch(variable)) with any of the case inside, the statements under the case that matches will be
executed. If none of the case is matched the statement under default will be executed.

Department of Electrical Engineering pg. 22


Syntax of switch statements #include<stdio.h>
#include<conio.h>
voidmain()
switch(variable) {
{ int choice;
case 1: printf("Enter a no between 1 and 5 : ");
Valid C Statements; scanf("%d",&choice);
break;
- switch(choice)
- {
case n: case 1:
Valid C Statements; {
break; printf("You choosed 1");
default: break;
Valid C Statements; }
break; case 2:
} {
printf("You choosed 1");
break;
}
case 3:
{
printf("You choosed 3");
break;
}
default :
{
printf("Wrong Choice");
break;
}
}
}

Figure 3: Switch Statement

Department of Electrical Engineering pg. 23


Lab activities:

Activity 1:

Write a C program to find if a number is even or odd. Program will ask the user to enter an
integer and will display on screen if the number is even or odd.

Activity 2:
Write a C program as depicted in the flowchart.

Department of Electrical Engineering pg. 24


Activity 3:
Write a C program to perform a desired arithmetic operation using switch statement and
declaring choice as char data type.

Activity 4:
Write a C program that asks the users to enter three numbers. Program will find and display
the minimum of the three numbers on the screen.

Department of Electrical Engineering pg. 25


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 26


Department of Electrical Engineering pg. 27
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
(10) limited competence competence competence
competence

Marks Obtained

Department of Electrical Engineering pg. 28


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering pg. 29


CSEE1121: Computer Programming Lab

Lab#03

Repetition Control Structures (For, While and Do-While


Loops)
Objective:
 Understanding of Repetition Control Structures
 Overview of syntax of for loops, while loops and do-while loops
 Understanding when to use a loop and where to use a specific loop
 Use of different types of loops in C program

In some programs, a certain task needs to be repeated or performed several times; For instance, one
wants to print the same words ten times. You could type ten printf function, but it is easier to use a
loop. The only thing you have to do is to setup a loop that executes the same printf function ten times.

There are two types of loop structures

Figure 1: Exit and Entry Controlled Loops


Department of Electrical Engineering pg. 30
There are three basic types of loops which are:

 “for loop”
 “while loop”
 “do while loop”

1. For Loop

For loop is entry controlled loop, the syntax of for loop is

int index=0;
for(index=0;index<6;index++)
{
printf("Hello word");
}

Figure 2: For Loop

2. While Loop

While loop is also a entry controlled loop, the syntax of while


loop is

while(condition)
{

Figure 3: While Loop

Department of Electrical Engineering pg. 31


3. do-While Loop
do-while loop is exit controlled loop. The
syntax of do-while loop is

do
{

}
while(condition)

Figure 4: do- While Loop

4. Break Statement

The break statement, when executed in a while, for, do…while or switch statement,
causes an immediate exit from that statement. Program execution continues with the next
statement. Common uses of the break statement are to escape early from a loop or to skip
the remainder of a switch statement.

Figure 5: Break Statement

Department of Electrical Engineering pg. 32


5. Continue Statement

The continue statement, when executed in a while, for or do…while statement, skips
the remaining statements in the body of that control statement and performs the next iteration
of the loop. In while and do…while statements, the loop-continuation test is evaluated
immediately after the continue statement is executed. In the for statement, the
increment expression is executed, then the loop-continuation test is evaluated. Earlier, we
said that the while statement could be used in most cases to represent the for statement.

Figure 7: Continue Statement

Department of Electrical Engineering pg. 33


6. Nested Loops
The placing of one loop inside the body of another loop is
called nesting. When you "nest" two loops, the outer loop takes
control of the number of complete repetitions of the inner
loop. While all types of loops may be nested, the most
commonly nested loops are for loops.

A program to print a rectangle.

void main()
{
int l=0,b=0;
printf("Enter length and Breadth:");
scanf("%d",&l);
scanf("%d",&b);

for(inti=0;i<b;i++)
{
for(int j=0;j<l;j++)
printf("*");

printf("\n");
}

Figure 5: Nested Loop

Department of Electrical Engineering pg. 34


Lab Activities:
Activity 1:
Write a program which takes an integer from user and calculates its factorial using while loop.

Activity 2:
Write a Program which calculates and displays N terms of Fibonacci’s Series using ‘for’ loop. Program
will ask the user to enter value of N.

Activity 3:
Write a Program which takes the base and perpendicular of a right-angle triangle as input and its
\\
hypotenuse, the program repeats itself and asks for inputs at every iteration until a character ‘e’ is
pressed to end the program. Use a ‘do-while’ loop. ( You may use Math Library functions where
required ).

Activity 4:
Write a program using ‘for’ loops which should display the following pattern on screen.
\\
******
*****
****
***
**
*

Department of Electrical Engineering pg. 35


Bonus Activity:
Write a program using ‘for’ loops which should display the following output

Bonus Activity:
Write a program using loops which should display the following outputs

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

Bonus activity:
Write a program using loops which should display the following output

Department of Electrical Engineering pg. 36


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 37


Department of Electrical Engineering pg. 38
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
(10) limited competence competence competence
competence

Marks Obtained

Department of Electrical Engineering pg. 39


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering pg. 40


CSEE1121: Computer Programming Lab

Lab#04

Introduction to User Defined Functions

Objective:

 Understanding the declaration and definition of functions


 Understanding how to call functions
 Overview of function return types
 Using arguments in functions
What is a function?

A function is a module or block of program code which deals with a particular task.

Making functions is a way of isolating one block of code from other independent blocks of code.

Functions serve two purposes.

 They allow a programmer to say: `this piece of code does a specific job which stands by itself
and should not be mixed up with anything else',
 Second they make a block of code reusable since a function can be reused in many different
contexts without repeating parts of the program text.

A function can take a number of parameters, do required processing and then return a value. There may
be a function which does not return any value.

You already have seen couple of built-in functions like printf(); Similar way you can define your own
functions in C language.

Consider the following chunk of code

int total = 10;


printf("Hello World");
total = total + l;

Department of Electrical Engineering pg. 41


To turn it into a function you simply wrap the code in a pair of curly brackets to convert it into a single
compound statement and write the name that you want to give it in front of the brackets:

Demo()
{
int total = 10;
printf("Hello World");
total = total + l;
}
Curved brackets after the function's name are required. You can pass one or more parameters to a
function as follows:

Demo( int par1, int par2)


{
printf("%d",part1, part2);
}
Function may not return a value or function may return any value to calling side

void Demo()
{
int total = 10;
printf("Hello World");
total = total + l;
}
If a function doesn’t return any value, then we use void before the name of the function.

Functions Types:

 Function which returns no value and has no arguments


 Function which returns no value and has arguments
 Function which returns a value and has no arguments
 Function which returns a value and has arguments

The following program is the example of a Function which has no arguments neither does it return a
value.

#include<stdio.h>
Void sum (void)
void sum()
{
int num1, num2;
printf("Enter num1:");
scanf("%d",&num1);
printf("Enter num2:");
scanf("%d",&num2);
printf("Result: %d",num1+num2);

Department of Electrical Engineering pg. 42


}
void main()
{
sum();
}
Calling the functions:

There are two ways to invoke functions in many programming languages


 call-by-value
 call-by-reference
When arguments are pass`ed by value, a copy of the argument’s value is made and passed to
the called function. Changes to the copy do not affect an original variable’s value in the caller.
When an argument is passed by reference, the caller allows the called function to modify the
original variable’s value.
Call-by-value should be used whenever the called function does not need to modify the value of
the caller’s original variable. This prevents the accidental side effetcs(variable modifications)
that so greatly hinder the development of correct and reliable software systems. Call-by-
reference should be used only with trusted called functions that need to modify the original
variable.
Compile the following code and see the output.

#include<stdio.h>
Void sum (int, int)
voidmsin()
{
int num1, num2;
printf("Enter num1:");
scanf("%d",&num1);
printf("Enter num2:");
scanf("%d",&num2);
sum(num1,num2)
printf("Result: %d",num1+num2);
}
void sum(int x, int y)
{
Int sum;
Sum = x+y;
Printf(Result:%d”, sum);
}

Program to calculate the square by passing the value in the function.

#include <stdio.h>
intsquare(inty ); /* function prototype */
/* function main begins program execution */
intmain(void )
Department of Electrical Engineering pg. 43
{
intx; /* counter */

/* loop 10 times and calculate and output square of x each time */


for( x = 1; x <= 10; x++ ) {
printf("%d ", square( x )); /* function call */
} /* end for */

printf("\n" );
return 0; /* indicates successful termination */
} /* end main */

/* square function definition returns square of parameter */


intsquare(inty ) /* y is a copy of argument to function */
{
return y * y; /* returns square of y as an int */
} /* end function square */

Function square is invoked or called in main within the printf statement. Function square receives a
copy of the value of x in the parameter y . Then square calculates y * y . The result is passed back to
function printf in main where square was invoked (line 14), and printf displays the result. This process is
repeated 10 times using the for repetition statement.

Department of Electrical Engineering pg. 44


Lab Activities:
Activity 1:
Write a user defined Function that will take rows and columns as input and print the following
pattern on the screen where t henumber of lines is equal to rows and number of ‘*’ in each
line is equal to columns. Function main() will ask the user to enter value of rows and columns
and call the function.

Activity 2:
Make a menu using functions, which should have the following options

1 to add two numbers

2 to subtract two numbers

3 to multiply two numbers

4 to divide two numbers

Use switch cases and do-while to complete this task

Activity 3:
Write a function that computes and returns XY. Function will take values of X and Y as input
arguments. Function main() will ask the user to enter X and Y.

Activity 4:
Write a function to compute least common multiple (LCM) of two numbers. F unction will
take two numbers as input and return LCM. Function main will ask the user to enter two
numbers and call the function.

Department of Electrical Engineering pg. 45


Bonus Activity:

Write a Function that will take a decimal number as input, convert it into binary and return the
binary number.

Bonus Activity:

Write a Function that will take a decimal number as input and checks if the number is palindromic
or not. If number is palindromic, function will return TRUE , otherwise FALSE.

Bonus Activity:

Implement distance formula between two points using functions.

Department of Electrical Engineering pg. 46


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 47


Department of Electrical Engineering pg. 48
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
(10) limited competence competence competence
competence

Marks Obtained

Department of Electrical Engineering pg. 49


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering pg. 50


Department of Electrical Engineering pg. 51
CSEE1121: Computer Programming Lab

Lab#05

Function Parameters and Recursive Functions

Objective:
 Overview of arguments of functions, i.e. what is meant by passing arguments by reference or by
value
 Understanding the scope of variables
 Understanding what is meant by a recursive function

Types of function arguments.

 Passing arguments by value


 Passing arguments by reference

Passing arguments by value:

Below is the example of a function which receives one parameter by value and checks wether the
number is even or odd.
void checkNum( int p1);
intmain()
{
Int a=21
checkNum( a );
}

void checkNum( intnum)


{
If(mum%2==0)
{
printf(“number is even”);
}
else
{
printf(“number is odd”);
}
}

Department of Electrical Engineering pg. 52


Calling function by reference:

The call by reference method of passing arguments to a function copies the reference of an argument into
the formal parameter. Inside the function, the reference is used to access the actual argument used in the
call. This means that changes made to the parameter affect the passed argument.
To pass the value by reference, argument reference is passed to the functions just like any other value. So
accordingly you need to declare the function parameters as reference types as in the following
function swap(), which exchanges the values of the two integer variables pointed to by its arguments.
#include<stdio.h>

/* function declaration */
void swap(int*x,int*y);

int main ()
{
/* local variable definition */
int a =100;
int b =200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values.


* &a indicates pointer to aie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a,&b);

return0;
}
/* function definition to swap the values */
void swap(int*x,int*y)
{
int temp;
temp =*x;/* save the value at address x */
*x =*y;/* put y into x */
*y = temp;/* put temp into y */
printf("After swap, value of a : %d\n", *x );
printf("After swap, value of b : %d\n", *y );

}
Scope of Variable:

A scope in any programming is a region of the program where a defined variable can have its existence
and beyond that variable cannot be accessed. There are three places where variables can be declared in
C programming language:

 Inside a function or a block which is called local variables,


 Outside of all functions which is called global variables.
 In the definition of function parameters which is called formal parameters.

Let us explain what are local and global variables and formal parameters.

Department of Electrical Engineering pg. 53


Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only by
statements that are inside that function or block of code. Local variables are not known to functions
outside their own. Following is the example using local variables. Here all the variables a, b and c are
local to main() function.

#include<stdio.h>

int main ()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a =10;
b =20;
c = a + b;

printf("value of a = %d, b = %d and c = %d\n", a, b, c);

return0;
}

Global Variables
Global variables are defined outside of a function, usually on top of the program. The global variables
will hold their value throughout the lifetime of your program and they can be accessed inside any of the
functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. Following is the example using global and local
variables:

#include<stdio.h>

/* global variable declaration */


int g;

int main ()
{
/* local variable declaration */
int a, b;

/* actual initialization */
a =10;
b =20;
g = a + b;

printf("value of a = %d, b = %d and g = %d\n", a, b, g);

return0;
}

Department of Electrical Engineering pg. 54


A program can have same name for local and global variables but value of local variable inside a function
will take preference. Following is an example:

#include<stdio.h>

/* global variable declaration */


int g =20;

int main ()
{
/* local variable declaration */
int g =10;

printf("value of g = %d\n", g);

return0;
}

When the above code is compiled and executed, it produces the following result:

value of g = 10

Formal Parameters
Function parameters, formal parameters, are treated as local variables with-in that function and they
will take preference over the global variables. Following is an example:

#include<stdio.h>

/* global variable declaration */


int a =20;

int main ()
/* local variable declaration in main function */
int a =10;

int b =20;
int c =0;

printf("value of a in main() = %d\n", a);


c =sum( a, b);
printf("value of c in main() = %d\n", c);

return0;
}

/* function to add two integers */


int sum(inta,int b)
{
printf("value of a in sum() = %d\n", a);
printf("value of b in sum() = %d\n", b);

return a + b;
}

Department of Electrical Engineering pg. 55


When the above code is compiled and executed, it produces the following result:

value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

Recursive Function:

A recursive function is a function that calls itself either directly or indirectly through another function.
We consider recursion conceptually first, and then examine several programs containing recursive
functions. Recursive problem-solving approaches have a number of elements in common. A recursive
function is called to solve a problem. The function actually knows how to solve only the simplest case(s),
or so-called base case(s). If the function is called with a base case, the function simply returns a result. If
the function is called with a more complex problem, the function divides the problem into two
conceptual pieces: a piece that the function knows how to do and a piece that it does not know how to
do. To make recursion feasible, the latter piece must resemble the original problem, but be a slightly
simpler or slightly smaller version. Because this new problem looks like the original problem, the
function launches (calls) a fresh copy of itself to go to work on the smaller problem—this is referred to
as a recursive call and is also called the recursion step. The recursion step also includes the keyword
return, because its result will be combined with the portion of the problem the function knew how to
solve to form a result that will be passed back to the original caller, possibly main.

Factorial using recursion Method:

#include<stdio.h>

int factorial(unsignedinti)
{
if(i<=1)
{
return1;
}
returni* factorial(i-1);
}
int main()
{
inti=15;
printf("Factorial of %d is %d\n",i, factorial(i));
return0;
}

Department of Electrical Engineering pg. 56


Fibonacci Series:
#include<stdio.h>

intfibonaci(inti)
{
if(i==0)
{
return0;
}
if(i==1)
{
return1;
}
returnfibonaci(i-1)+fibonaci(i-2);
}

int main()
{
inti;
for(i=0;i<10;i++)
{
printf("%d\t%n",fibonaci(i));
}
return0;
}

Math Library Functions:

Figure 1: Math Library Functions


Lab Activities:

Department of Electrical Engineering pg. 57


Activity 1:
write a user defined function to solve the quadratic equation. Function will take a, b
and c as input and compute and return both the roots of the quadratic equation. In
main(), ask the user to enter values of a, b and cand call the user defined function. At
the end, main() will display both the roots returned by the function on screen. (Hint :
Use parameters by reference to return both the roots)

Activity 2:
Write a C-Program that will generate a random number in the range given by the user. Function
main() will ask the user to enter the range and call a user defined function. Function will
generate the random number in the given range. Function main() will display the number on
screen. Use global variable to store the random number. (Use function rand() for random
number generation, Library : stdlib.h )

Activity 3:
Write a recursive function that computes and returns XY . In main() ask the user to enter X and
Y. Function main() will also display the result on the screen.

Activity 4:
Write a Recursive function to multiply two numbers. Call the function in main() to multiply the
numbers given by the user.

Department of Electrical Engineering pg. 58


Bonus Activity 1:
Write a function that will take polar coordinates (r, 𝜃) as input and convert and return
thecorresponding Cartesian coordinates (x, y). Main() will display the coordinates on screen
𝑥 = 𝑟 𝐶𝑜𝑠 ( 𝜃 )

𝑦 = 𝑟 𝑆𝑖𝑛 ( 𝜃 )

Bonus Activity 2:
Implement game of Dice using library function rand(). Program will randomly generate
outcome of Dice and ask the user to guess the outcome. If user is correct, program will
display, ‘You Win’, otherwise program will display ‘You Lose’. At the end, program will ask the
user, ‘Press ‘y’ to repeat, any other key to exit.

Bonus Activity 3:
Write a Recursive function to find the GCD of two numbers. Call the function in main() to find
the GCD of the numbers entered by the user. Function main() will display the GCD on screen.

Department of Electrical Engineering pg. 59


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 60


Department of Electrical Engineering pg. 61
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
(10) limited competence competence competence
competence

Marks Obtained

Department of Electrical Engineering pg. 62


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering pg. 63


CSEE1121: Computer Programming Lab

Lab#06

One Dimensional Arrays


Objective:

 Understand the use of arrays in C-Language


 Understand the declaration of one-dimensional arrays
 Understand the declaration of two-dimensional arrays

C programming language provides a data structure called the array, which can store a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.

Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows:

type arrayName[arraySize];

Department of Electrical Engineering pg. 64


This is called a single-dimensional array. The arraySize must be an integer constant greater than zero
and type can be any valid C data type. For example, to declare a 10-element array called balance of type
double, use this statement:

double balance[10];

Now balance is avariable array which is sufficient to hold upto 10 double numbers.

Initializing Arrays

You can initialize array in C either one by one or using a single statement as follows:

double balance[5]={1000.0,2.0,3.4,17.0,50.0};

The number of values between braces { } can not be larger than the number of elements that we declare
for the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if
you write:

double balance[]={1000.0,2.0,3.4,17.0,50.0};

You will create exactly the same array as you did in the previous example. Following is an example to
assign a single element of the array:

balance[4]=50.0;

The above statement assigns element number 5th in the array with a value of 50.0. All arrays have 0 as
the index of their first element which is also called base index and last index of an array will be total size
of the array minus 1. Following is the pictorial representation of the same array we discussed above:

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element
within square brackets after the name of the array. For example:

double salary = balance[9];

The above statement will take 10th element from the array and assign the value to salary variable.
Following is an example which will use all the above mentioned three concepts viz. declaration,
assignment and accessing arrays:

#include<stdio.h>

Department of Electrical Engineering pg. 65


int main ()
{
int n[10];/* n is an array of 10 integers */
inti,j;

/* initialize elements of array n to 0 */


for(i=0;i<10;i++)
{
n[i]=i+100;/* set element at location i to i + 100 */
}

/* output each array element's value */


for(j =0; j <10;j++)
{
printf("Element[%d] = %d\n", j, n[j]);
}

return0;
}

When the above code is compiled and executed, it produces the following result:

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Strings and character array in C language


String is a sequence of characters that is treated as single data item and terminated by null character
‘\0’. Remember that C language does not sport strings as a data type. A string is actually one-
dimensional array of characters in C language. These are often used to create meaningful and readable
programs.

For example: The string “hello word” contains 12 characters including ‘\0’ character which is
axiomatically added by the compiler at the end of the string.

Decelerating and initializing a string variables


There are different ways to initialize a character array variable.

char name [10]= “StudyTonight”;

char name[10]={‘L’,’e’,’’s’,’s’,’o’,’n’,’s’,’\0’}

Department of Electrical Engineering pg. 66


Remember that when you initialize a character array by listing all its characters separately then you must
supply the ‘\0’ character explicitly.

Some examples of illegal initialization of character array are

char ch[4]=”Hello” //illegal

char str[5]=”Hello” //illegal

Passing Arrays to Functions:


To pass an array argument to a function, specify the array’s name without any brackets.
For example, if array hourlyTemperatures has been defined as:

inthourlyTemperatures[HOURS_IN_A_DAY ];

the function call

modifyArray(hourlyTemperatures, HOURS_IN_A_DAY );

passes array hourlyTemperatures and its size to function modifyArray.Recall that all arguments in C are
passed by value. C automatically passes arrays to functions by referencethecalled functions can modify
the element values in the callers’ original arrays. The name of the array evaluates to the address of the
first element of the array. Because the starting address of the array is passed, the called function knows
precisely where the array is stored. Therefore, when the called function modifies array elements in its
function body, it’s modifying the actual elements of the array in their original memory locations.

#include<stdio.h>
float average(float age[]);

int main()
{
floatavg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
avg = average(age); /* Only name of array is passed as argument. */
printf("Average age=%.2f", avg);
return0;

Department of Electrical Engineering pg. 67


}

float average(float age[])


{
inti;
floatavg, sum = 0.0;
for (i = 0; i<6; ++i) {
sum += age[i];
}
avg = (sum / 6);
returnavg;
}

Department of Electrical Engineering pg. 68


 mam ko next sunday tak pg 70 tak submit karwana hay

Lab Activities:
Activity 1:
Write a program that gets input from user in one dimensional integer array of size 10. Your program
should find and display maximum value in the array on Screen.

.
Activity 2:
Write a program in which you declare two integer arrays of size 10 and get input from user in both the
arrays. After getting the input you are required to interchange elements in both the array and then
display both arrays on Screen.

Activity 3:
Write a user defined function that will take an integer array and its size as input. Function will count
odd numbers in the array and return the count. In main() define an array of size 10 and ask the user to
fill the array. After this, main () will call the user defined function and pass the array. Main will also
display the count returned by the function.

Activity 4:
Write a program that defines a char array of size 50. Program will ask the user to enter a String.
Program should count the number of times vowel characters appear in the string and display the
count on screen.

Department of Electrical Engineering pg. 69


Bonus Activity 1:
Write a program that defines an array of size 20 and type float. Program should fill the array with the
terms of series shown below. Program will also display the array on Screen.

1 , 1/22 , 1/32 , 1/42 , … , 1/N2

Bonus Activity 2:
Write a Program that will ask the user to enter two strings. Program will compare two strings using
Loops and tell if the strings are same or not.

Bonus Activity 3:
Write a User defined function that will take an integer array and its size as input. Function will reverse
the elements in the array. In Main(), ask the user to fill an array of size 10. Main() will call the function
to reverse the elements in the array. Main () will also display the array on screen, before and after
calling the function.

Department of Electrical Engineering pg. 70


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 71


Department of Electrical Engineering pg. 72
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
(10) limited competence competence competence
competence

Marks Obtained

Department of Electrical Engineering pg. 73


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering pg. 74


CSEE1121: Computer Programming Lab

Lab#07

Multi-Dimensional Arrays
Objective:

 Understand the use of Multi-Dimensional arrays in C


 Understand the declaration of two-dimensional arrays
 Usage of 2D arrays as function arguments

Two-dimensional array are those type of array, which has finite number of rows and finite number of
columns. The declaration form of 2-dimensional array is

Data_type Array_name [row size][column size];

The type may be any valid type supported by C. The rule for giving the array name is same as the
ordinary variable. The row size and column size should be an individual constant.

The following declares a two-dimensional 3 by 3 array of integers and sets the first and last elements to
be 10.

int matrix [3][3];


matrix[0][0] = 10;
matrix[2][2] = 10;

#include<stdio.h>
int main()
{

/* 2D array declaration*/
intdisp[3][5];

/*Counter variables for the loop*/


inti, j;

Department of Electrical Engineering pg. 75


for(i=0;i<=2;i++)
{
for(j=0;j<=4;j++)
{

printf("Enter value for disp[%d][%d]:",i, j);

scanf("%d",&disp[i][j]);

}
return0;
}

Initialization of 2D Array
There are many ways to initialize two Dimensional arrays –

intdisp[2][4]={
{10,11,12,13},

{14,15,16,17}

};
OR

intdisp[2][4]={10,11,12,13,14,15,16,17};
Things which you must consider while initializing 2D array –
You must remember that when we give values during one dimensional array declaration, we don’t need
to mention dimension. But that’s not the case with 2D array; you must specify the second dimension
even if you are giving values during the declaration. Let’s understand this with the help of few examples

/* Valid declaration*/
intabc[2][2]={1,2,3,4}
/* Valid declaration*/
intabc[][2]={1,2,3,4}
/* Invalid declaration – you must specify second dimension*/
intabc[][]={1,2,3,4}
/* Invalid because of the same reason mentioned above*/
intabc[2][]={1,2,3,4}

Department of Electrical Engineering pg. 76


Store Data into 2D array
...
intabc[5][4];
.....

/*loop for first dimension which is 5 here*/


for(i=0;i<=4;i++)
{

/*loop for second dimension of array which is 4 in this example*/


for(j=0;j<=3;j++)
{

printf("Enter value for abc[%d][%d]:",i, j);

scanf(“%d”,&abc[i][j]);

}
In above example, I have a 2D array – abc of integer type. I have used nested for loops to store data.
Conceptually you can consider above array like this –

However, the actual representation of this array in memory would be something like

Department of Electrical Engineering pg. 77


Passing 2D array to a function:
C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way
to pass such arrays to a function depends on the way used to simulate the multiple dimensions:

One way is to use an array of arrays. This can only be used if your array bounds are fully determined at
compile time.
#include<stdio.h>

voiddisplayNumbers(intnum[2][2]);

int main()

intnum[2][2], i, j;

printf("Enter 4 numbers:\n");

for (i = 0; i<2; ++i)

for (j = 0; j <2; ++j)

scanf("%d", &num[i][j]);

// passing multi-dimensional array to displayNumbers function

displayNumbers(num);

return0;

voiddisplayNumbers(intnum[2][2])

Department of Electrical Engineering pg. 78


// Instead of the above line,

// void displayNumbers(intnum[][2]) is also valid

inti, j;

printf("Displaying:\n");

for (i = 0; i<2; ++i)

for (j = 0; j <2; ++j)

printf("%d\n", num[i][j]);

Department of Electrical Engineering pg. 79


Lab Activities:
Activity 1:
Write a C-Program that gets a 4x4 2D array as input from user and display it on the Screen in Tabular
form shown below:

1834
2678
9171
2242

Activity
. 2:
Write a C-Program that gets two 3x3 Matrices as input from user and store in 2D arrays. Program will
add the two matrices and display the result on screen. 1 8 3 4
1111 1111 = 2222
2222 2222 = 4444
3333 3333 = 9999
4444 4444 = 8888

Activity 3:
Write a user defined function that gets a 3x3 matrix as input, computes and returns its transpose. In
main() ask the user to enter a 3x3 matrix and call the function. Function main() will also display both
the original and the transpose matrix on Screen.
Activity 4:
Write a C-Program that will take two 2x2 matrices as input from user, check whether matrix
use
multiplication is possible; if so, program will multiply the two matrices and display the result on
screen.

Department of Electrical Engineering pg. 80


Bonus Activity 1:
Write a C-Program that will take a 3x3 matrix as input from user and check if matrix is lower triangular
or not.

300

580

147

Bonus Activity 2:
Write a C-Program that will take a 3x3 matrix as input from user and check if matrix is identity matrix
or not.

100

010

001

Bonus Activity 3:
Write a C-Program that will define a 2D character array of size 10x50 and ask the user to enter names
of 10 students in the array. Program will also display name of the students on screen.

Department of Electrical Engineering pg. 81


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 82


Department of Electrical Engineering pg. 83
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
(10) limited competence competence competence
competence

Marks Obtained

Department of Electrical Engineering pg. 84


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering pg. 85


CSEE1121: Computer Programming Lab

Lab#08

Strings in C Language
Objective:
 Understanding Strings
 Using String.h library Functions

Strings and character array in C language


String is a sequence of characters that is treated as single data item and terminated by null character
‘\0’. Remember that C language does not sport strings as a data type. A string is actually one-
dimensional array of characters in C language. These are often used to create meaningful and readable
programs.

For example: The string “hello word” contains 12 characters including ‘\0’ character which is
axiomatically added by the compiler at the end of the string.

Decelerating and initializing a string variables

There are different ways to initialize a character array variable.

char name [10]= “StudyTonight”;

char name[10]={‘L’,’e’,’’s’,’s’,’o’,’n’,’s’,’\0’}

Remember that when you initialize a character array by listing all its characters separately then you
must supply the ‘\0’ character explicitly.

Some examples of illegal initialization of character array are

char ch[4]=”Hello” //illegal

char str[5]=”Hello” //illegal

C does not support string as the data type. However, is allows us to represent strings as character arrays.
It can be declared as –

Department of Electrical Engineering pg. 86


char name[size];

Here char is character data type. This is must for specifying the data type as string. name is the valid
variable name given to the string and ‘size’ determines the number of characters in the string. For
example:

char star[10];
char book[13];
char phone[ ];

Analysis
Here ‘star’ is the character array or a string that can store up to 10 elements of type char. It can be
represented as:

charstar[10];

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

However, star can also store shorter sequences than 10 characters. Similarly, ‘book’ can store 13
characters. It can be represented as

char book[13];

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

char phone[ ];

Here phone array does not have size specified. This initializes an upsized character array, phone, with a
string constant. Later when the compiler sees the statement, it will figure out the total memory space
needed to hold the string constant plus an extra null character added by the compiler itself and allocates
the memory space.

Initializing a String
As other type of arrays, strings can also be initialized at compile time and at run time. The process of
initializing the strings at compile time is to write the string literal within double quotes. Compile time
initialization is called as static initialization. Compile time initialization can be done in three ways. They
are given below.
Type 1.char name[9] = “Umar”;
Type 2. char stream[7] = {`H', `e', `l', `l', `o', `!', `\0'};
Type 3.char str[] = "I like C.";

Initialization after Declaration

char s[10] = " Web Design";


is not the same as

Department of Electrical Engineering pg. 87


char s[10];
s = "Web Design"; /*Illegal declaration.*/
This generates a compiler error. The assignment operator cannot be used with a string already declared.

String Constants versus Character Constants


A string constant is a series of characters enclosed in double quotes (" ").
On the other hand, a character constant is a character enclosed in single quotes (` `). When a character
variable ch and a character array str are initialized with the same character, x, such as the following, char
ch = `x'; char str[] = "x";
One byte is reserved for the character variable ch, and two bytes are allocated for the character array
str. The reason that an extra byte is needed for str is that the compiler has to append a null character to
the array.

Input data to string


This is also called as run time initialization. The integers, character and float data types are read by using
functions such as scanf(), gets,etc. Similarly, to read a string two functions are used. They are

1. scanf()
2. gets ()

Reading Strings Using scanf ( )


To read strings using scanf() format specifier %s is used with the function scanf(). For example

char name[10];

To input data in to char array ’name’, scanf function and %s is used as given below.

scanf("%s",name);

Note that the %s format specifier doesn’t require the ampersand (&) symbol before the variable name.
The major limitation of scanf() is that it reads until occurrence of first separator a white space characters
such as space character, tab or new line and store it into given variable. For example if the input literal is
“How are you?”. Then the scanf statement will read only the word ‘How’ into the variable name.

To overcome this limitation, gets() and getchar() functions are used.

Reading Strings using gets( )


The gets() functions reads the string from the keyboard including spaces until the enter key is not
pressed. The getchar() function is used to get a single charater. The gets() and getchar() functions are
defined in stdio.h library file. For example

char line[100];
printf("Enter a line:\n");
gets(line);
puts("Entered input is :\n");
puts(line);

Department of Electrical Engineering pg. 88


The gets() function keeps reading characters from the standard input stream until a new line character
or end-of-file is encountered. Instead of saving the new line character, the gets() function appends a null
character to the array that is referenced by the argument to the gets() function.

Print strings
To output data of the given string two functions are used. They are
1) printf()
2) puts ()

Printing strings using printf()


The printf statement along with format specifier %s is used to print strings on the screen. The format %s
can be used to display an array of characters that is terminated by the null character. For example,

printf(“%s”, name);

can be used to display the entire contents of the array name.

printf() expects to receive a string as an additional parameter when it sees %s in the format string. This
additional parameter

– Can be from a character array.


– Can be another literal string.
– Can be from a character pointer (more on this Pointer chapter).

printf knows how much to print out because of the NULL character at the end of all strings. When
printf() encounters a null\0, it stops printing. The string variable can be printed out with precision using
printf() statement. For example

printf("%7.3s",name)

This specifies that only the first 3 characters have to be printed in a total field width of 7 characters &
right justified in the allocated width by default. We can include a minus sign to make it left justified (%-
7.3). For example consider the following program.

– printf("|%5s|","Have a Happy Day");


• | Have a Happy Day|
– printf("|%-5s|","Have a Happy Day");
• |Have a Happy Day |
– printf("|%25.12s|","Have a Happy Day");
• | Have a Happy|
– printf("|%.12s|","Have a Happy Day");
• |Have a Happy

Department of Electrical Engineering pg. 89


Printing strings using puts( )
The puts function is a much simpler output function than printf for string printing. Prototype of puts is
defined in stdio.h For example:

char sentence[] = "This is strings in C \n";


puts(sentence);

This Prints out:


This is strings in C
Consider a simple program to understand string input and output functions.

#include <stdio.h>
void main()
{
char str[80] ; Char str2[45];
printf("Enter a string: ") ;
gets(str1) ;
printf("Enter another string: ") ;
scanf(“%s“,str2); /*Reads upto first white space character*/
Printf(“output of first string:\n”);
printf("%s" , str1\n);
Printf(“output of second string:\n”);
puts(“str2 “)
}

Result
Input:
Enter a string: This is c language.
Enter another string: This is strings

Output
Output of first string: This is c language
Output of second string: This

Built-in String Functions


C does not provide any operators for string. Because of this C has built in string functions in its library. C
library supports a large number of string handling functions that can be used to perform many of the
string manipulations. Some of the string functions are given below. To do all the operations described
here it is essential to include string.h library header file in the program.

Department of Electrical Engineering pg. 90


Main Functions in the Library string.h

strcpy() function
C does not allow you to assign the characters to a string directly.For example as in the statement
name=”Java”; Instead use the strcpy() function. The strcpy() function works almost like a string-
assignment operator. The syntax of the function is

strcpy(string1,string2);

Strcpy() function assigns the contents of string2 to string1.The string2 may be a character array variable
or a string constant.

strcpy(Name,”Java”);
strcpy(city1, city2);

This will assign the contents of the string variable city2 to the string variable city1.The size of the array
city1 should be large enough to receive the contents of city2, if not compiler will lodge an error.

strcat() function
The process of appending the characters of one string to the end of other string is called concatenation.
The strcat() function joins two strings together. strcat(string1,string2)
Here string1 & string2 are character arrays. When the function strcat is executed string2 is appended to
string1.The string at string2 remains unchanged.

Department of Electrical Engineering pg. 91


Example
strcpy(string1,”Web”);
strcpy(string2,”Mining”);
Printf(“%s”, strcat(string1,string2);

From the above program segment the value of string1 becomes webmining. The string at str2 remains
unchanged as mining. The variation in this function is strncat(str1,str2,n) .This concatenates the n
integer letters to str1. For example,

strncat(stri,name,4);

This concatenates first 4 letters of string name to string stri.

strlen() function
This function counts and returns the number of characters in a string. The length does not include a null
character. The syntax is n=strlen(string); Where n is integer variable, which receives the value of length
of the string.

strstr() function
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
The matching process does not include the terminating null-characters, but it stops there.

strtok() function
A sequence of calls to this function split str into tokens, which are sequences of contiguous characters
separated by any of the characters that are part of delimiters.
On a first call, the function expects a C string as argument for str, whose first character is used as the
starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the
position right after the end of the last token as the new starting location for scanning.

Department of Electrical Engineering pg. 92


Lab Activities:
Activity 1:
Write a C-Program that will define a 2D character array of size 10x40 and ask the user to enter names
of 10 students in the array. Program will search name of the student in the list and if Name found
displays a message “Name Found” otherwise “Name not Found”. (Use String Library Function
‘strcmp’)

.
Activity 2:
Write a C Program that will read two strings entered by the user. Program will interchange first 5
characters in both the strings using ‘strncpy’. Display the updated strings on screen.

Activity 3:
Write a user defined function that takes a string as input and checks if it is palindrome or not. If string
is palindrome, function will display ‘Palindrome String’ otherwise ‘Not Palindrome’. In main() ask the
user to enter a string and call the function.

Activity 4:
Write a C Program that will count and display the words in a sentence entered by the user.

Department of Electrical Engineering pg. 93


Bonus Activity 1:
Write a C Program that will ask the user to enter a sentence and a word. Program will count the
number of times the word occurs in the sentence and display the count on the Screen. ( You
may use String Library Function strstr() )

Bonus Activity 2:
Write your own function to replace ‘strlen()’ function in String Library. Function will take a
string as input and return count of characters in the string.

Bonus Activity 3:
Write a C Program that will read a string from user and display its Morse Code on the screen.
Use the Table below for Morse Code conversion.

Department of Electrical Engineering pg. 94


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 95


Department of Electrical Engineering pg. 96
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
(10) limited competence competence competence
competence

Marks Obtained

Department of Electrical Engineering pg. 97


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering pg. 98


CSEE1121: Computer Programming Lab

Lab#09

Pointers in C Language
Objective:
 Understanding Pointers
 Passing pointers to functions
 Understanding array manipulation using pointers

Pointers are a fundamental part of C. A pointer is a derived data type in ‘C’. It is built from any one of
the primary data type available in ‘C’ programming language. Pointers contain memory addresses as
their values. C uses pointers because of following advantages namely,
 It is the only way to express some computations.
 It produces compact and efficient code.
 It provides a very powerful tool to solve complex problems.
 It reduces the complexity and length of the program.
C uses pointers explicitly with:
 Arrays
 Structures
 Functions

How variables are stored in memory?

Consider the following variables declared in a program:

char name;
int number;
float height;

When a variable is defined the compiler allocates a real memory address for the variable. For character
one byte, float four bytes and int two bytes are allocated generally. The following diagram illustrates
how the above declared variables might be arranged in memory along with their addresses

Department of Electrical Engineering pg. 99


What is a Pointer?

A pointer is a special variable that holds the address of the memory location of another variable.
Another variable could be anything. It could be a float, int, char, double, etc. Consider the following
statement:

int number =5;

For integer variable quantity let the address of the variable be 5078.This can be diagrammatically
presented as given below.

During the execution of program computer always associates the integer variable number with
address 5078. The value 5 can be accessed by using either the variable number or the address
of it which is 5078. Since memory addresses are simply numbers they can be assigned to some
variables which can be stored in memory like any other variables. Such variables that hold
memory addresses are called as ‘pointer variables’ the pointer variable is nothing but a variable
that contains an address of another variable in memory. When a pointer contains address of
integer variable, such pointer is called integer pointer. Similarly float, char pointers contain the
address of char and float data type.

Pointer Declaration

In C every variable must be declared before it is used. Since pointer is a special variable, its declaration is
also different. An operator called dereference operator or indirection operator is used to declare a
Pointer. It is represented by *(asterisk). The ‘*’ symbol appears in C language in four different situations
with four different meanings. Two of these are well known.

i. Comments/*…*/
ii. Arithmetic operator for multiplication as in a*b
iii. Declaring pointer variable using *(dereference operator)

Department of Electrical Engineering pg. 100


Usage of deference operator in comment can be easily recognized. Multiplication needs two operands;
this can also be easily recognized. When it appears in a declaration as int *p, read it is read as p is a
pointer to an integer. The syntax of pointer declaration is

data-type *variable-name;

Here data type can be int, float, char etc and the dereference operator before the int variable variable-
name tells that it is a pointer variable. Hence the pointer variable variable-name holds the address of
another variable of the same data type. For example,

A pointer is declared by assigning an asterisk (*) in front of the variable name in the declaration
statement.

int x; /* define x */
int *ptr; /* define a pointer to x */
int *p; //p is a pointer to an integer.

Similarly, pointer to char and float can be declared

char *q; //q is a pointer to a char.


float *fp; //fp is a pointer to float.

The "dereferencing operator" the asterisk can also be is used as follows:

*ptr = 7;

This will copy 7 to the address pointed to by ptr. Thus if ptr"points to" (contains the address of) x, the
above statement will set the value of x to 7. That is, when the '*' is used this way, it is referring to the
value of that which ptris pointing to, not the value of the pointer itself.

Pointer Declaration Styles

The dereference operator (*) can appear anywhere between the data type name and the pointer
variable name as shown below.

int * p; /* style 1 between the data type and variable */


int *p; /* style 2 Close to variable */
int* p; /* style 3 close to data type. */

Multiple Declarations

Multiple pointers of same data type can be declared as given below.

int *p, x, *q;

Department of Electrical Engineering pg. 101


Here p and q are pointer variables and x is integer variable.

Pointer Initialization

Consider the declaration

inti, j,*p;

It declares a pointer variable p that can point to an integer. Just this kind of declaration, doesn’t specify
where a integer pointer p has to point at particular. In other words it does not say anything about which
particular integer variable address it has to hold, either of inti or of int j, in this case.To explicitly
specifywhere variable a pointer has to point to, a unary operator called reference or address operator
(&) is used. The reference operator (&) cannot be applied to expressions, constants, or register
variables. To initialize the pointer variable, reference operator (&) is used with pointer variable. To
understand different types of initialization, consider the following examples,

inti, j, *p;
p = &i;

This causes p pointer variable to point at i the integer data type. Here
 is the indirection operator
 & is the address operator

A pointer is said to be a null pointer when its value is 0. Remember, a null pointer can never point to
valid data. To set a null pointer, simply assign 0 to the pointer variable. For example:
char *pc;
int *pt;
pt=pc=0;
Here pt and pc pointers become null pointers after the integer value of 0 is assigned to them.

Pointer Expressions

To understand the working of pointers consider the below expressions.

intx,y;
int *ptr1,*ptr2;

1) ptr1=&x;

The memory address of the variable x is assigned to pointer variable ptr1.

2) y=*ptr1

Pointer variable ptr1 is holding the address. The content of that address is assigned to the variable y, not
the memory address.

Department of Electrical Engineering pg. 102


3) ptr1=&x;
ptr2=ptr1;

Ptr1 holds the address of the variable due to first declaration. In the second declaration content of ptr1
i.e. the address of x is transferred to ptr2.Hence both ptr1, ptr2 both will be holding the same address.

4) For better understanding of the pointers consider some of the invalid declarations given
below.

i) int x;
int ptr1;
ptr1=&x;

Error: pointer declaration must have the prefix of dereference (*) operator.

ii) float p;
float*var;
var=y;

Error: While assigning variable to the pointer variable the address operator (&) must be used
along with the variable.

iii) int x;
char *name;
name=&x;

Error: Mixing of data type is not allowed.

Pointer Arithmetic

Pointer is a variable .Some arithmetic operations can be performed with pointers. C language supports
four arithmetic operators which can be performed with pointers .They are
 addition +
 subtraction
 Pointer increment
 Pointer decrement

Pointer increment and decrement

Integer, float, char, double data type pointers can be incremented and decremented. For all these data
types both prefix and post fix increment or decrement is allowed. Integer pointers are incremented or
decremented in the multiples of two. Similarly character by one, float by four and double pointers by
eight etc.

Let int*p;
Department of Electrical Engineering pg. 103
P++ /*valid*/
++p /*valid*/
p-- /*valid*/
--p /*valid*/

This is illustrated in the below program.

#include <stdio.h>
int main()
{
int *p1,p;
float *f1,f;
char *c1,c;
p1=&p;
f1=&f;
c1=&c;
printf(“Memory address before increment:\n
int=%p\n,float=%p\n, char=%p\n“,p1,f1,c1);
p1++;
f1++;
c1++;
printf(“Memory address after increment:\n int=%p\n, float=%p\n,
char=%p\n“,p1,f1,c1);
return 0;
}

Output:
Memory address before increment:
int=0045AF19 /*int Occupies two bytes*/
float=0045AF2B /*float occupies four bytes*/
char= 0045AF3E /*character occupies one byte*/
Memory address after increment:
int=0045AF1B
float=0045AF2F
char= 0045AF3F

Compile the following program

#include <stdio.h>
int main()
{
int x;
int *p;

Department of Electrical Engineering pg. 104


x=1000;
p=&x;
printf(“Pointer value = %d\n”,p);
printf(“Pointer plus one =%d\n”,p+1);
return 0;
}
An example output can be:
Pointer value = 22F455
Pointer plus one = 22F439
Analysis:
223455+1=223439! That is pointer magic! How does C justify that? Well, 223455 is not just a number, C
knows it is the address of an integer that takes 4 locations. So 223455,223456, 223457 and 223458 are
all together held by the integer. So C interprets +1 as next free location and gives the answer
223459.Remember that it need not be continuation of memory location, when a pointer is incremented.

Arrays and pointers

An array is actually very much like a pointer. We can declare the arrays first element of array can be
declared as a1[0] or as int *a1 because a[0] is an address and *a is also an address. Hence the
correspondence between array and pointers can be understood in the following section

Pointers in 1D array

In the example given below, character pointer ptr variable that will hold the address of the character
array str.

// array

char str[6] = "Hello";

// pointer

char *ptr = str;

Note! Array variable points at the beginning address of the allocated memory locations for the array.

In the above code we are storing the beginning address of the array str in the pointer variable ptr. So,
ptr points at the array str.

Department of Electrical Engineering pg. 105


Incrementing pointer variable
When we increment the pointer variable it points to the next memory location based on the size of the
data type.

So, ptr character pointer variable is pointing at the first memory location of the one dimensional
character array str.

And char data type is of size 1 byte. So, if the first memory location is 1000 and ptr is initially pointing at
that memory location then ptr++ will make the ptr variable point at 1001 memory location.

Similarly, if a pointer variable is of data type int and let’s say the size of integer is 2 bytes then, if the
pointer is initially pointing at the memory location 1000 then after incrementing its value using
the ++ operator it will point at the next memory location 1002 holding the next integer data.

2D Arrays and pointers

We have created the two dimensional integer array num so, our pointer will also be of type int.

We will assign the address of the first element of the array num to the pointer ptr using the address
of & operator.

int *ptr = &num[0][0];

Accessing the elements of the two dimensional array via pointer


The two dimensional array num will be saved as a continuous block in the memory. So, if we increment
the value of ptr by 1 we will move to the next block in the allocated memory.

Department of Electrical Engineering pg. 106


In the following code we are printing the content of the num array using for loop and by incrementing
the value of ptr.

#include <stdio.h>
int main(void) {
// 2d array
intnum[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// pointer ptr pointing at array num
int *ptr = &num[0][0];
// other variables
int
ROWS = 3,
COLS = 4,
TOTAL_CELLS = ROWS * COLS,
i;
// print the elements of the array num via pointer ptr
for (i = 0; i< TOTAL_CELLS; i++) {
printf("%d ", *(ptr + i));
}
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12

Address mapping
We can compute the address of an element of the array by using the rows and columns of the array. For
this we use the following formula.

arr[i][j] = baseAddress + [(i x no_of_cols + j) x size_of_data_type]

Where, arr is a two dimensional array. i and j denotes the ith row and jth column of the array.

baseAddress denotes the address of the first element of the array. And no_of_cols is the total number
of columns in the row.

And size_of_data_type is the size of the type of the pointer. If the type is int then size_of_data_type = 2
bytes and if the type is char then size_of_data_type = 1 bytes.

Department of Electrical Engineering pg. 107


For example, in the case of num array the baseAddress = 1000, no_of_cols = 4 and size_of_data_type =
2.

So, we can compute the memory address location of the element num[2][3] as follows.

// address of element at cell 2,3


num[2][3] = baseAddress + [(i x no_of_cols + j) x size_of_data_type]
= 1000 + [(2 x 4 + 3) x 2]
= 1000 + [(8 + 3) x 2]
= 1000 + 22
= 1022

Accessing the value of the two dimensional array via pointer using row and column of the
array
If we want to get the value at any given row, column of the array then we can use the value at the
address of * operator and the following formula.

arr[i][j] = *(ptr + (i x no_of_cols + j))

Where, arr is a two dimensional array and i and j denotes the ith row and jth column of the array.
Department of Electrical Engineering pg. 108
ptr holds the address of the first element of the array.

And no_of_cols denotes the total number of column in the row of the array.In the following example we
are finding the value at the location 2nd row and 3rd column of the array num.

// value at num[2][3] where, i = 2 and j = 3


num[2][3] = *(ptr + (i x no_of_cols + j))
= *(ptr + (2 x 4 + 3))
= *(ptr + 11)

Array of Pointers
In computer programming, an array of pointers is an indexed set of variables in which the variables
are pointers (a reference to a location in memory).

Pointers are an important tool in computer science for creating, using, and destroying all types of data
structures. An array of pointers is useful for the same reason that all arrays are useful: it allows you to
numerically index a large set of variables.

Below is an array of pointers in C: it sets each pointer in one array to point to an integer in another and
then prints the values of the integers by dereferencing the pointers (printing the value in memory that
the pointers point to).

#include <stdio.h>

constint ARRAY_SIZE = 5;

int main ()
{
/* first, declare and set an array of five integers: */
intarray_of_integers[] = {5, 10, 20, 40, 80};

/* next, declare an array of five pointers-to-integers: */


inti, *array_of_pointers[ARRAY_SIZE];

for ( i = 0; i< ARRAY_SIZE; i++)


{
/* for indices 1 through 5, set a pointer to
point to a corresponding integer: */
array_of_pointers[i] = &array_of_integers[i];
}

for ( i = 0; i< ARRAY_SIZE; i++)


{
Department of Electrical Engineering pg. 109
/* print the values of the integers pointed to
by the pointers: */
printf("array_of_integers[%d] = %d\n", i, *array_of_pointers[i] );
}

return 0;
}

The output of the above program is:


array_of_integers[0] = 5
array_of_integers[1] = 10
array_of_integers[2] = 20
array_of_integers[3] = 40
array_of_integers[4] = 80

Department of Electrical Engineering pg. 110


Lab Activities:
Activity 1:
Write a user defined function that will find both minimum and maximum of an array and return both
the values. Function should user pointer to access the array. In main() generate random numbers to fill
the array and call the function. Function main() will also display both minimum and maximum
numbers on screen.

Activity 2:
Write a C program using pointers that takes two 3x3 arrays from user as input and add them. Result is
stored in a 3rd 3x3 array. Program should also display the result on screen in tabular form.

Activity 3:
Rewrite the strcpy() function. Function will copy one array onto other using pointers. In main() ask the
user to enter two strings and call the function. Function main() will also display both strings on screen.

Activity 4:
Write a C-Program that asks the user to enter name of 10 people and store it in an array. Program will
only display names that have more than 5 characters. Use array of pointers to Access List of names.

Department of Electrical Engineering pg. 111


Department of Electrical Engineering pg. 112
Bonus Activity 1:
Write a C-Program that defines 3 1-D arrays of size 5. Define an array of pointers and use it to access
the 1-D arrays like A 2-D array. Ask the user to fill the arrays and display its contents on screen in
tabular form.

Bonus Activity 2:

Define two arrays of size 10 and a third array of size 20. Ask the user to enter values in both the arrays.
Access the arrays using pointers and Copy contents of both the arrays in the third array in interleaved
form. Display all three arrays on screen.

Department of Electrical Engineering pg. 113


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 114


Department of Electrical Engineering pg. 115
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
(10) limited competence competence competence
competence

Marks Obtained

Department of Electrical Engineering pg. 116


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering pg. 117


CSEE1121: Computer Programming Lab

Lab#10

Structures in C Language
Objective:
 Understanding Structures in C Language
 Understanding the declaration of structure
 Accessing Structure Members

Introduction to Structures
Structure is a user-defined data type in C which allows you to combine different data types to store a
particular type of record. Structure helps to construct a complex data type in more meaningful way. It is
somewhat similar to an Array. The only difference is that array is used to store collection of similar data
types while structure can store collection of any type of data.

Structure is used to represent a record. Suppose you want to store record of Student which consists of
student name, address, roll number and age. You can define a structure to hold this information.

Defining a structure
struct keyword is used to define a structure. struct define a new data type which is a collection
of different type of data.

Syntax :

structstructure_name
{
//Statements
};

Example of Structure
struct Book
{
char name[15];
int price;
int pages;
Department of Electrical Engineering pg. 118
};

Here the struct Book declares a structure to hold the details of book which consists of three data fields,
namely name, price and pages. These fields are called structure elements or members. Each member
can have different data type, like in this case, name is of char type and price is of int type etc. Book is
the name of the structure and is called structure tag.

Declaring Structure Variables

struct Student
{
char[20] name;
int age;
introllno;
} ;

struct Student S1 , S2;//declaring variables of Student

Declaring Structure Variables with Structure definition

struct Student
{
char[20] name;
int age;
introllno;
} S1, S2 ;

Here S1 and S2 are variables of structure Student. However, this approach is not much recommended.

Accessing Structure Members

Structure members can be accessed and assigned values in number of ways. Structure member has no
meaning independently. In order to assign a value to a structure member, the member name must be
linked with the structure variable using dot . operator also called period or member access operator.

struct Book
{
char name[15];
int price;
int pages;
} b1 , b2 ;

b1.price=200;//b1 is variable of Book type and price is member of Book

We can also use scanf() to give values to structure members through terminal.
Department of Electrical Engineering pg. 119
scanf(" %s ", b1.name);
scanf(" %d ", &b1.price);

Structure Initialization

Like any other data type, structure variable can also be initialized at compile time.

struct Patient
{
float height;
int weight;
int age;
};

struct Patient p1 = { 180.75 , 73, 23 };//initialization


or,
struct patient p1;
p1.height = 180.75;//initialization of each member separately
p1.weight = 73;
p1.age = 23;

Array of Structure

We can also declare an array of structure. Each element of the array representing a structure variable.

Example :struct employee emp[5];

The above code define an array emp of size 5 elements. Each element of array emp is of type employee

#include<stdio.h>
#include<conio.h>
struct employee
{
charename[10];
intsal;
};

struct employee emp[5];


inti,j;
void ask()
{
for(i=0;i<3;i++)
{
printf("\nEnter %dst employee record\n",i+1);
printf("\nEmployee name\t");
scanf("%s",emp[i].ename);
printf("\nEnter employee salary\t");
scanf("%d",&emp[i].sal);

Department of Electrical Engineering pg. 120


}
printf("\nDisplaying Employee record\n");
for(i=0;i<3;i++)
{
printf("\nEmployee name is %s",emp[i].ename);
printf("\nSlary is %d",emp[i].sal);
}
}
void main()
{
clrscr();
ask();
getch();
}

Nested Structures

Example :
struct student
{
char[30] name;
int age;
struct address
{
char[50] locality;
char[50] city;
intpincode;
};
};

Memory Allocation for Structure

If we create an object of some structure, then compiler allocate contiguous memory for the data
members of the structure. The size of allocated memory is at least the sum of sizes of all data members.
The compiler can use padding and in that case there is will be unused space created between two data
members. The padding is done for the alignment of data member which makes the access to the
member faster. However you can control the padding behavior and can stop compiler to generated
extra space.
The data members of structure is accessed with the help of the base address of the structure and the
offset of the data member in the structure object.
Let us see this in an example.

#include <stdio.h>
#include <string.h>

struct student
{
int id1;
int id2;
char a;
char b;

Department of Electrical Engineering pg. 121


float percentage;
};

intmain()
{
inti;
struct student record1 = {1, 2, 'A', 'B', 90.5};

printf("size of structure in bytes : %d\n",


sizeof(record1));

printf("\nAddress of id1 = %u", &record1.id1 );


printf("\nAddress of id2 = %u", &record1.id2 );
printf("\nAddress of a = %u", &record1.a );
printf("\nAddress of b = %u", &record1.b );
printf("\nAddress of percentage = %u",&record1.percentage);

return 0;
}

Output:

size of structure in bytes : 16


Address of id1 = 675376768
Address of id2 = 675376772
Address of a = 675376776
Address of b = 675376777
Address of percentage = 675376780

There are 5 members declared for structure in above program. In 32-bit compiler, 4 bytes of memory is
occupied by int datatype. 1 byte of memory is occupied by char datatype and 4 bytes of memory is
occupied by float datatype.

Please refer below table to know from where to where memory is allocated for each datatype in
contiguous (adjacent) location in memory.

Department of Electrical Engineering pg. 122


Lab Activities:
Activity 1:
Define a structure ‘Point’ that represents a point in 2D Cartesian Coordinate System. Structure has two
members ‘x’ and ‘y’. In main, define variables of type Point and get data of two points from user.
Program should calculate the distance between the two points and display it on screen.

Activity 2:
Define
. a structure ‘ComplexNumber’ with two members ‘Real’ and ‘Complex’. In main define variables
of type ‘ComplexNumber’. Program will multiply two complex numbers and store the result in a
variable of type ComplexNumber’. Ask the user to enter two complex numbers and display the
resultant complex number on screen.

Activity 3:
Define a structure named ‘Student’ to represent students. Structure will have members ‘Name’ of
type string, ‘Marks’ of type int and ‘Grade’ of type char. In main define an array of size 10 and type
‘student’ and ask the user to enter name and marks of 10 students. Program will find the grade of all
the students and display their Name, Marks and grade on screen. (If marks of students are above 50 ,
student has ‘P’ grade , otherwise students has ‘F’ grade).
.

Activity 4:
Define a structure named ‘Book’ to represent books. Structure will have members ‘Title’ of type string,
‘Pages’ of type int and ‘Price’ of type float. In main define an array of type ‘Book’ with 10 elements and
ask the user to enter data of 10 books. Program will find the book with maximum price and display its
name, price and number of pages on screen.
Department of Electrical Engineering pg. 123
.
Bonus Activity 1:
Define a structure named ‘Patient’ to represent patients in a Hospital. Structure will have members
‘Name’ of type string, ‘PatientID’ of type int and ‘NumberOfVisits’ of type int. In main define an array
of type ‘Patient’ and ask the user to enter data of 10 Patients. Program will search a patient with his
PatientID and if found, program will display his Name, PatientID and Number of Visits on Screen.
.

Bonus Activity 2:
Define a structure named ‘Customer’ to represent Customers in a shopping mall. Structure will have
members ‘Name’ of type string, ‘ContactNumber’ of type int and ‘TotalBill’ of type float. In main define
an array of type ‘Customer’ and ask the user to enter data of 10 Customers. Program will find and
Design Lab # 10
display Name, Contact Number and Total Bill of all the customers whose bill is above Rs. 1000.
.

Department of Electrical Engineering pg. 124


Department of Electrical Engineering pg. 125
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 126


Department of Electrical Engineering pg. 127
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
(10) limited competence competence competence
competence

Marks Obtained

Department of Electrical Engineering pg. 128


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering pg. 129


CSEE1121: Computer Programming Lab

Lab#11

Nested Structures and Union


Objective:
 Understanding nested structures
 Passing Structures as function arguments
 Understanding union

Nested Structures
Nested structure in C is nothing but structure within structure. One structure can be declared inside
other structure as we declare structure members inside a structure. The structure variables can be a
normal structure variable or a pointer variable to access the data.

Structure within a structure in c using normal variable:

This program explains how to use structure within structure in C using normal variable.
“student_college_detail’ structure is declared inside “student_detail” structure in this program. Both
structure variables are normal structure variables.

Please note that members of “student_college_detail” structure are accessed by 2 dot(.) operator
and members of “student_detail” structure are accessed by single dot(.) operator.

#include <stdio.h>
#include <string.h>

structstudent_college_detail
{
intcollege_id;
charcollege_name[50];
};

structstudent_detail
{
int id;
char name[20];
float percentage;
// structure within structure
structstudent_college_detailclg_data;
}stu_data;

Department of Electrical Engineering pg. 130


int main()
{
structstudent_detailstu_data = {1, "ALI", 90.5, 71145,
"CUST University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);

printf(" College Id is: %d \n",


stu_data.clg_data.college_id);
printf(" College Name is: %s \n",
stu_data.clg_data.college_name);
return 0;
}

OUTPUT:
Id is: 1
Name is: ALI
Percentage is: 90.500000

College Id is: 71145


College Name is: CUST University

Structure within structure in C using pointer variable:

This program explains how to use structure within structure in C using pointer variable.
“student_college_detail’ structure is declared inside “student_detail” structure in this program. one
normal structure variable and one pointer structure variable is used in this program.

Please note that combination of .(dot) and ->(arrow) operators are used to access the structure member
which is declared inside the structure.

#include <stdio.h>
#include <string.h>

structstudent_college_detail
{
intcollege_id;
charcollege_name[50];
};

structstudent_detail
{
int id;
char name[20];
float percentage;
// structure within structure
Department of Electrical Engineering pg. 131
structstudent_college_detailclg_data;
}stu_data, *stu_data_ptr;

int main()
{
structstudent_detailstu_data = {1, "ALI", 90.5, 71145,
"CUST UNIVERSITY"};
stu_data_ptr = &stu_data;

printf(" Id is: %d \n", stu_data_ptr->id);


printf(" Name is: %s \n", stu_data_ptr->name);
printf(" Percentage is: %f \n\n",
stu_data_ptr->percentage);

printf(" College Id is: %d \n",


stu_data_ptr->clg_data.college_id);
printf(" College Name is: %s \n",
stu_data_ptr->clg_data.college_name);

return 0;
}
OUTPUT:

Id is: 1
Name is: ALI
Percentage is: 90.500000

College Id is: 71145


College Name is: CUST UNIVERSITY

Passing structure to function in C:

It can be done in 3 ways.

 Passing structure to a function by Value


 Passing structure to a function by Address(Reference)
 No need to pass a structure – Declare structure variable as global

Passing structure to function in C by value:


In this program, the whole structure is passed to another function by value. It means the whole
structure is passed to another function with all members and their values. So, this structure can be
accessed from called function. This concept is very useful while writing very big programs in C.

#include <stdio.h>
#include <string.h>

Department of Electrical Engineering pg. 132


struct student {
int id;
char name[20];
float percentage;
};

voidfunc(struct student record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "ALI");
record.percentage = 86.5;

func(record);
return 0;
}

voidfunc(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
OUTPUT:
Id is: 1

Name is: ALI

Percentage is: 86.500000

Passing structure to function in C by address:


In this program, the whole structure is passed to another function by address. It means only the address
of the structure is passed to another function. The whole structure is not passed to another function
with all members and their values. So, this structure can be accessed from called function by its address.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

voidfunc(struct student *record);

int main()
{
Department of Electrical Engineering pg. 133
struct student record;

record.id=1;
strcpy(record.name, "ALI");
record.percentage = 86.5;

func(&record);
return 0;
}

voidfunc(struct student *record)


{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}

OUTPUT:
Id is: 1
Name is: ALI

Percentage is: 86.500000

Union in C:

C Union is also like structure, i.e. collection of different data types which are grouped together. Each
element in a union is called member.

 Union and structure in C are same in concepts, except allocating memory for their members.
 Structure allocates storage space for all its members separately.
 Whereas, Union allocates one common storage space for all its members
 We can access only one member of union at a time. We can’t access all member values at the same
time in union. But, structure can access all member values at the same time. This is because, Union
allocates one common storage space for all its members. Where as Structure allocates storage
space for all its members separately.
 Many union variables can be created in a program and memory will be allocated for each union
variable separately.
 Below table will help you how to form a C union, declare a union, initializing and accessing the
members of the union.
Using normal variable Using pointer variable

Syntax: Syntax:
union tag_name union tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
Department of Electrical Engineering pg. 134
Example: Example:
union student union student
{ {
int mark; int mark;
char name[10]; char name[10];
float average; float average;
}; };

Declaring union using Declaring union using


normal variable: pointer variable:
union student report; union student *report, rep;

Initializing union using


Initializing union using pointer variable:
normal variable: union student rep = {100,
union student report = “Mani”, 99.5};
{100, “Mani”, 99.5}; report = &rep;

Accessing union members Accessing union members


using normal variable: using pointer variable:
report.mark; report -> mark;
report.name; report -> name;
report.average; report -> average;

DIFFERENCE BETWEEN STRUCTURE AND UNION IN C:


C Structure C Union

Union allocates one common storage space for


all its members.
Union finds that which of its member needs
Structure allocates storage space for all high storage space over other members and
its members separately. allocates that much space

Structure occupies higher memory Union occupies lower memory space over
space. structure.

We can access all members of structure We can access only one member of union at a
at a time. time.

Structure example: Union example:

Department of Electrical Engineering pg. 135


struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };

For above structure, memory allocation


will be like below.
int mark – 2B For above union, only 8 bytes of memory will
char name[6] – 6B be allocated since double data type will occupy
double average – 8B maximum space of memory over other data
Total memory allocation = 2+6+8 = 16 types.
Bytes Tota

Example Program :-
#include <stdio.h>

union job {

char name[32];

float salary;

intworkerNo;

} job1;

int main(){

printf("Enter name:\n");

scanf("%s", &job1.name);

printf("Enter salary: \n");

scanf("%f", &job1.salary);

printf("Displaying\nName :%s\n", job1.name);

printf("Salary: %.1f", job1.salary);

return 0;
Department of Electrical Engineering pg. 136
}

Output

Enter name

Hillary

Enter salary

1234.23

Displaying

Name: f%Bary

Salary: 1234.2

Department of Electrical Engineering pg. 137


Lab Activities:
Activity 1:
Define a structure ‘Date’ that has three members ‘Day’, ‘Month’ and ‘Year’ of type int. Define another
structure, ‘Employee’ that also has three members named ‘ Name of type string, ‘Salary’ of type Float
and ‘DOB’ of type Date. In main(), ask the user to enter data of 10 employees. Program will display the
data of all employees who were born in 1995.

Activity 2:
Define a structure ‘Point’ that represents a point in 2D Cartesian Coordinate System. Structure has two
.
members ‘x’ and ‘y’. Also define a user defined function ‘ComputeDistance’. Function will take two
structures of type Point as input, compute and return the distance between the points. Structures will
be passed by value. In main(), define variables of type Point and get data of two points from user. Call
the function, ComputeDistance and pass both the points. Main() will also display distance returned by
the function on screen.
.

Activity 3:
Define a structure named ‘Time’ . Structure will have three members, ‘Seconds’, ‘Minutes’, and ‘Hours
of type int. Also define a function that takes a structure of type Time as input. Function will conver the
time into Seconds and return the value. Structure will be passed by Reference to the function. In
main(), define a variable of type Time and get data from user. Call the function and display the seconds
returned by the function on screen.
.

Activity 4:
Define a struct named ‘Book’ to represent books. Struct will have members ‘Title’ of type string,
‘Pages’ of type int and ‘Price’ of type float. Also define a union named ‘Journal’ to represent research
articles. Union will also have three members named ‘Title’ of type string, ‘Pages’ of type int and ‘Price’
of type float. In main define one variable each of type Book and Journal and ask the user to enter the
data. Use function sizeof() to display size of both the variables on screen. Also display data of both the
variables on screen. Does both the variables show data correctly ?
.

Department of Electrical Engineering pg. 138


Bonus Activity 1:
Create union floatingPoint with members float f, double d and longdouble x. Write a program that
inputs values of type float, double and long double and stores thevalues in union variables of type
union floatingPoint. Each union variable should be printed as afloat, a double and a long double. Do
the values always print correctly?
.

Bonus Activity 2:
Define a ‘HealthProfile’ structure for a person. The structure’s members should include the person’s
firstname, last name, gender, date of birth (consisting of separate attributes for the month, day and
yearof birth), height and weight. Your program should have a function that receivesdata of 50 persons
and stores in an array of type ‘HealthProfile’. The program also shouldinclude functions that calculate
and return the user’s age in years, using his date of birth. In main() main call the user defined
functions to get data of 50 individuals and display their age on screen.

Department of Electrical Engineering pg. 139


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 140


Department of Electrical Engineering pg. 141
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
(10) limited competence competence competence
competence

Marks Obtained

Department of Electrical Engineering pg. 142


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering pg. 143


CSEE1121: Computer Programming Lab

Lab#12

File Handling in C Language


Objective:
 Understanding the concept of File Handling
 File Modes in C Language
 Reading and Writing in Sequential Access Files
 Reading and Writing in Random Access Files

File Handling in C Language


A file represents a sequence of bytes on the disk where a group of related data is stored. File is created
for permanent storage of data. It is a readymade structure.In C language, we use a structure pointer of
file type to declare a file.

FILE *fp;

C provides a number of functions that helps to perform basic file operations. Following are the
functions:

Function Description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

Department of Electrical Engineering pg. 144


fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point

Opening a File or Creating a File

The fopen() function is used to create a new file or to open an existing file.

General Syntax :

*fp = FILE *fopen(const char *filename, const char *mode);


Here filename is the name of the file to be opened and mode specifies the purpose of opening the file.
Mode can be of following types,
*fp is the FILE pointer ( FILE *fp ), which will hold the reference to the opened (or created) file.

Mode Description

r opens a text file in reading mode

w opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

Department of Electrical Engineering pg. 145


a+ opens a text file in both reading and writing mode

rb opens a binary file in reading mode

wb opens or create a binary file in writing mode

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode

Closing a File

The fclose() function is used to close an already opened file.


General Syntax:
intfclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the
file. This EOF is a constant defined in the header file stdio.h.

Input/Output operation on File

In the above table we have discussed about various file I/O functions to perform reading and writing on
file. getc() and putc() are simplest functions used to read and write individual characters to a file.
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");

Department of Electrical Engineering pg. 146


while( (ch = getchar()) != EOF) {
putc(ch,fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
while( (ch = getc()) != EOF)
printf("%c",ch);
fclose(fp);
}

Reading and Writing from File using fprintf() and fscanf()

#include<stdio.h>
#include<conio.h>
struct emp
{
char name[10];
int age;
};

void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);

Department of Electrical Engineering pg. 147


printf("%s %d", e.name, e.age);
}
while( !feof(q) );
getch();
}
In this program, we have created two FILE pointers and both are referring to the same file but in
different modes. fprintf() function directly writes into the file, while fscanf() reads from the file, which
can then be printed on console using standard printf() function.

Difference between Append and Write Mode

Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write
in a file. In both the modes, new file is created if it doesn't exists already.

The only difference they have is, when you open a file in the write mode, the file is reset, resulting in
deletion of any data already present in the file. While in append mode this will not happen. Append
mode is used to append or add data to the existing data of file(if any). Hence, when you open a file in
Append(a) mode, the cursor is positioned at the end of the present data in the file.

Reading and Writing in a Binary File

A Binary file is similar to the text file, but it contains only large numerical data. The Opening modes are
mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.
fwrite(data-element-to-be-written, size_of_elements,
number_of_elements, pointer-to-file);
fread() is also used in the same way, with the same arguments like fwrite() function. Below mentioned is
a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the lazy dog";
FILE *bfp= fopen("test.txt", "wb");
if (bfp) {
fwrite(mytext, sizeof(char), strlen(mytext), bfp) ;
fclose(bfp) ;
}
fseek(), ftell() and rewind() functions

Department of Electrical Engineering pg. 148


 fseek() - It is used to move the reading control to different positions using fseek function.
 ftell() - It tells the byte location of current position of cursor in file pointer.
 Rewind- It moves the control to beginning of the file.

Lab Activities:
Activity1:
Write a C Program that gets the Name, Reg. No. and CGPA of 10 Students from user. Program will
store this data in a Sequential Access file ‘StudentData.txt’ and close the file. Double Click the File to
check if data is written correctly.

Activity 2:
.
Write a C Program that will open the Sequential Access file written in Activity 1, read the data of 10
Students and display it on the screen.

Activity 3:
Define a structure ‘Book’ with members ‘Title’, Pages and Price. In main() get data of 10 books from
user and store in a Random Access file.

Activity 4:
Write a C Program to open a Random Access File and copy all of its data in a new file.

Department of Electrical Engineering pg. 149


Bonus Activity 1:
Write a C Program to compare two files in Random Access mode. Program should display if files are
identical or not.

Bonus Activity 2:

Write a C Program to Append the Content of one File at the end of Another File

Bonus Activity 3:

Write a C Program to calculate file size in Bytes. Program will open the file in Random Access Mode.
Program should also display file size on screen.

Department of Electrical Engineering pg. 150


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering pg. 151


Department of Electrical Engineering pg. 152
LABORATORY SKILLS ASSESSMENT (Psychomotor)

Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the skills specific to the skills specific to the
required by the task with some task without task without any
task errors significant errors error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostlycorrect, but correct,with no
with majority of some contradictory may contain known errors, and no
contradictory conditions occasional errors or redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in perfect
procedural knowledge knowledge ways
knowledge
Program Program does Program Program produces Program produces
Correctness not produce approaches correctanswers or correctanswers or
(20) correct answers correct answers or appropriateresults for appropriateresults
orappropriate appropriate results most inputs. for all inputs tested.
results for formost inputs, but
most inputs. cancontain
miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree of
Department of Electrical Engineering pg. 153
(10) limited competence competence competence
competence

Marks Obtained

LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems

Department of Electrical Engineering pg. 154


polished.

Marks Obtained

Department of Electrical Engineering pg. 155

You might also like