Computer Programming Lab Manual
Computer Programming Lab Manual
Name: ___________________________________
Reg No: ___________________________________
pg. ii
S.N0 List of Experiments
7 Multi-Dimensional Arrays
8 Strings in C Language
9 Pointers in C Language
10 Structures 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
Objectives:
To familiarize the students with:
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
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.
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.
Example 1. Design an algorithm and the corresponding flowchart for adding the test scores as
givenbelow:
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.
There are three type of control structures available in C language as shown in the figure below.
1- Sequential
2- Selection
3- Repetition
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
2. C - Program Structure
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
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.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.
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.
Local Variables
Global Variables
data_typevariable_name;
For example, if you want to declare a variable of type integer then the syntax will be
int number;
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.
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.
#include stdio.h
void main
scanf(“%d”,i);
intI,j
k=i+j;
print(“%d,k);
*****************
* 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
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
Total Marks: 40
Marks Obtained
Lab#02
If
If-Else
Nested If-Else
Switch Statement
Syntax: #include<stdio.h>
//this program demonstrate the simple if
if(condition) statement
{ voidmain()
Statement1; {
..... int number1;
Statement n; int 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
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.
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.
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
Total Marks: 40
Marks Obtained
Lab#03
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.
“for loop”
“while loop”
“do while loop”
1. For Loop
int index=0;
for(index=0;index<6;index++)
{
printf("Hello word");
}
2. While Loop
while(condition)
{
do
{
}
while(condition)
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.
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.
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");
}
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.
\\
******
*****
****
***
**
*
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
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
Total Marks: 40
Marks Obtained
Lab#04
Objective:
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.
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.
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:
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:
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);
#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);
}
#include <stdio.h>
intsquare(inty ); /* function prototype */
/* function main begins program execution */
intmain(void )
Department of Electrical Engineering pg. 43
{
intx; /* counter */
printf("\n" );
return 0; /* indicates successful termination */
} /* end main */
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.
Activity 2:
Make a menu using functions, which should have the following options
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.
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:
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
Total Marks: 40
Marks Obtained
Lab#05
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
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 );
}
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 );
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:
Let us explain what are local and global variables and formal parameters.
#include<stdio.h>
int main ()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a =10;
b =20;
c = a + b;
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>
int main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a =10;
b =20;
g = a + b;
return0;
}
#include<stdio.h>
int main ()
{
/* local variable declaration */
int g =10;
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>
int main ()
/* local variable declaration in main function */
int a =10;
int b =20;
int c =0;
return0;
}
return a + b;
}
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.
#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;
}
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;
}
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.
𝑦 = 𝑟 𝑆𝑖𝑛 ( 𝜃 )
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.
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
Total Marks: 40
Marks Obtained
Lab#06
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];
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:
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:
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>
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
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.
char name[10]={‘L’,’e’,’’s’,’s’,’o’,’n’,’s’,’\0’}
inthourlyTemperatures[HOURS_IN_A_DAY ];
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;
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.
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.
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
Total Marks: 40
Marks Obtained
Lab#07
Multi-Dimensional Arrays
Objective:
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
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.
#include<stdio.h>
int main()
{
/* 2D array declaration*/
intdisp[3][5];
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}
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
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");
scanf("%d", &num[i][j]);
displayNumbers(num);
return0;
voiddisplayNumbers(intnum[2][2])
inti, j;
printf("Displaying:\n");
printf("%d\n", num[i][j]);
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.
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.
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
Total Marks: 40
Marks Obtained
Lab#08
Strings in C Language
Objective:
Understanding Strings
Using String.h library Functions
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.
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.
C does not support string as the data type. However, is allows us to represent strings as character arrays.
It can be declared as –
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.";
1. scanf()
2. gets ()
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.
char line[100];
printf("Enter a line:\n");
gets(line);
puts("Entered input is :\n");
puts(line);
Print strings
To output data of the given string two functions are used. They are
1) printf()
2) puts ()
printf(“%s”, name);
printf() expects to receive a string as an additional parameter when it sees %s in the format string. This
additional parameter
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.
#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
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.
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);
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.
.
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.
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.
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
Total Marks: 40
Marks Obtained
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
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
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:
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)
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.
*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.
The dereference operator (*) can appear anywhere between the data type name and the pointer
variable name as shown below.
Multiple Declarations
Pointer Initialization
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
intx,y;
int *ptr1,*ptr2;
1) ptr1=&x;
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.
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;
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
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*/
#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
#include <stdio.h>
int main()
{
int x;
int *p;
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
// pointer
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.
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.
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.
#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.
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.
So, we can compute the memory address location of the element num[2][3] as follows.
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.
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.
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};
return 0;
}
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.
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.
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
Total Marks: 40
Marks Obtained
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.
struct Student
{
char[20] name;
int age;
introllno;
} ;
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.
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 ;
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;
};
Array of Structure
We can also declare an array of structure. Each element of the array representing a structure variable.
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;
};
Nested Structures
Example :
struct student
{
char[30] name;
int age;
struct address
{
char[50] locality;
char[50] city;
intpincode;
};
};
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;
intmain()
{
inti;
struct student record1 = {1, 2, 'A', 'B', 90.5};
return 0;
}
Output:
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.
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.
.
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
Total Marks: 40
Marks Obtained
Lab#11
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.
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;
OUTPUT:
Id is: 1
Name is: ALI
Percentage is: 90.500000
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;
return 0;
}
OUTPUT:
Id is: 1
Name is: ALI
Percentage is: 90.500000
#include <stdio.h>
#include <string.h>
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "ALI");
record.percentage = 86.5;
func(record);
return 0;
}
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
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;
}
OUTPUT:
Id is: 1
Name is: ALI
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;
}; };
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.
Example Program :-
#include <stdio.h>
union job {
char name[32];
float salary;
intworkerNo;
} job1;
int main(){
printf("Enter name:\n");
scanf("%s", &job1.name);
scanf("%f", &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
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 ?
.
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.
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
Total Marks: 40
Marks Obtained
Lab#12
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are the
functions:
Function Description
The fopen() function is used to create a new file or to open an existing file.
General Syntax :
Mode Description
Closing a 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");
#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);
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.
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
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.
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.
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
Total Marks: 40
Marks Obtained